转自:http://blog.csdn.net/kikilizhm/article/details/7858405
这里给出在linux下的简单socket网络编程的实例,使用tcp协议进行通信,服务端进行监听,在收到客户端的连接后,发送数据给客户端;客户端在接受到数据后打印出来,然后关闭。程序里有详细的说明,其中对具体的结构体和函数的实现可以参考其他资料。
程序说明: 这里服务器的端口号和ip地址使用固定的设置,移植时可以根据具体情况更改,可以改写为参数传递更好,这里为了方便,使用固定的。
移植时服务端可以不用更改,编译后可直接运行;客户端将ip改为服务器的地址,然后编译运行。可以使用netstat 进行查看相应的运行状态。
-
- #include <stdlib.h>
- #include <sys/types.h>
- #include <stdio.h>
- #include <sys/socket.h>
- #include <linux/in.h>
- #include <string.h>
-
- int main()
- {
- int sfp,nfp;
- struct sockaddr_in s_add,c_add;
- int sin_size;
- unsigned short portnum=0x8888;
-
- printf("Hello,welcome to my server !\r\n");
- sfp = socket(AF_INET, SOCK_STREAM, 0);
- if(-1 == sfp)
- {
- printf("socket fail ! \r\n");
- return -1;
- }
- printf("socket ok !\r\n");
-
- bzero(&s_add,sizeof(struct sockaddr_in));
- s_add.sin_family=AF_INET;
- s_add.sin_addr.s_addr=htonl(INADDR_ANY);
- s_add.sin_port=htons(portnum);
- if(-1 == bind(sfp,(struct sockaddr *)(&s_add), sizeof(struct sockaddr)))
- {
- printf("bind fail !\r\n");
- return -1;
- }
- printf("bind ok !\r\n");
- if(-1 == listen(sfp,5))
- {
- printf("listen fail !\r\n");
- return -1;
- }
- printf("listen ok\r\n");
-
- while(1)
- {
- sin_size = sizeof(struct sockaddr_in);
- nfp = accept(sfp, (struct sockaddr *)(&c_add), &sin_size);
- if(-1 == nfp)
- {
- printf("accept fail !\r\n");
- return -1;
- }
- printf("accept ok!\r\nServer start get connect from %#x : %#x\r\n",ntohl(c_add.sin_addr.s_addr),ntohs(c_add.sin_port));
-
- if(-1 == write(nfp,"hello,welcome to my server \r\n",32))
- {
- printf("write fail!\r\n");
- return -1;
- }
- printf("write ok!\r\n");
- close(nfp);
-
- }
- close(sfp);
- return 0;
- }
-
- #include <stdlib.h>
- #include <sys/types.h>
- #include <stdio.h>
- #include <sys/socket.h>
- #include <linux/in.h>
- #include <string.h>
-
- int main()
- {
- int cfd;
- int recbytes;
- int sin_size;
- char buffer[1024]={0};
- struct sockaddr_in s_add,c_add;
- unsigned short portnum=0x8888;
-
- printf("Hello,welcome to client !\r\n");
- cfd = socket(AF_INET, SOCK_STREAM, 0);
- if(-1 == cfd)
- {
- printf("socket fail ! \r\n");
- return -1;
- }
- printf("socket ok !\r\n");
- bzero(&s_add,sizeof(struct sockaddr_in));
- s_add.sin_family=AF_INET;
- s_add.sin_addr.s_addr= inet_addr("192.168.1.104");
- s_add.sin_port=htons(portnum);
-
- printf("s_addr = %#x ,port : %#x\r\n",s_add.sin_addr.s_addr,s_add.sin_port);
-
- if(-1 == connect(cfd,(struct sockaddr *)(&s_add), sizeof(struct sockaddr)))
- {
- printf("connect fail !\r\n");
- return -1;
- }
- printf("connect ok !\r\n");
- if(-1 == (recbytes = read(cfd,buffer,1024)))
- {
- printf("read data fail !\r\n");
- return -1;
- }
- printf("read ok\r\nREC:\r\n");
-
- buffer[recbytes]='\0';
- printf("%s\r\n",buffer);
-
- getchar();
- close(cfd);
- return 0;
-
-
-
- }
|
请发表评论