首页 Soft PlugIn RAN乱 Dev开发 Info资料 English WAP 留言 登陆 注册
-
Posted by Yippee | 评论(1) | 引用(0) | 阅读2117次
Llinux下基本SOCKET编程-服务器端

调试环境:MAGIC C++ 3.0 CYGWIN 资料来源:http://www.chinalinuxpub.com/read.php?wid=180 Linux环境下的Socket编程 BAIDU了一些资料,这个基本编译OK,注释详细,函数和结构定义基本能从MSDN上找到说明。

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#define SERVPORT 3333 /*服务器监听端口号 */
#define BACKLOG 10 /* 最大同时连接请求数 */
main()
{
int sockfd,client_fd; /*sock_fd:监听socket;client_fd:数据传输socket */
struct sockaddr_in my_addr; /* 本机地址信息 */
struct sockaddr_in remote_addr; /* 客户端地址信息 */
int sin_size=0;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("socket创建出错!"); exit(1);
}
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(SERVPORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero),8);
if (bind(sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr))  == -1) {
perror("bind出错!");
exit(1);
}
printf("%s\n",inet_ntoa(my_addr.sin_addr));
if (listen(sockfd, BACKLOG) == -1) {
perror("listen出错!");
exit(1);
}
while(1) {
sin_size = sizeof(struct sockaddr_in);
if ((client_fd = accept(sockfd, (struct sockaddr *)&remote_addr, &sin_size)) == -1) {
perror("accept出错");
continue;
}
printf("received a connection from %s\n", inet_ntoa(remote_addr.sin_addr));
 if (!fork()) { /* 子进程代码段 */
 if (send(client_fd, "Hello, you are connected!\n", 26, 0) == -1)
 perror("send出错!");
close(client_fd);
exit(0);
}
close(client_fd);
}


字体:

Permanant URI永久地址 http://www.shengfang.org/blog/p/linuxsocktsrv.php
Trackback URI引用地址 http://www.shengfang.org/blog/tb.php?tb_id=1119928231

2005年6月28日11:10星期二  [Info资料] 追踪此文的RSS
Yippee在 2005年6月28日11:15星期二 评论:
fork Linux下的多进程编程 http://www.lslnet.com/linux/docs/linux-2739.htm

称呼:    登陆   注册
   不注册,但记住我的信息
邮件:
(非必须)
评论: [UBB代码帮助]
粗体 斜体 下划线 链接 水平线 引用



验证码: 请输入你看见的数字
关闭UBB      提交时自动将内容复制到剪贴板

公告
Fire and Motion!

统计信息
[Yippee]||[统计]||日志:1858
在线: 8||用户: 2577 [列表]
今日:398||到访:2886462
Rss:897742||评论:1605

最新日志

最新评论

友情链接

日历
2008 - 08
     12
3456789
10111213141516
17181920212223
24252627282930
31      

最新引用

搜索

归档

杂项
Get RSS Feed (Version 2.0)
Get Atom Feed (Version 0.3)
编码:  UTF-8