工作以来,写了很多socket相关的代码。磕磕碰碰,走了很多弯路,也积累了一些东西,今天正好整理一下。为了证明不是从书上抄来的,逻辑会有点乱(借口,呵呵)!知识点的介绍也不会像书上说的那么详细和精准,毕竟个人水平也就这样了。当然,主要还是以上手为主,不过分剖析原理性内容。一些陌生的函数要用到的头文件,使用man查看一下就能解决了。既然该文的名称为“快速上手”,那个人认为下述内容都不存在水分,都是必须要掌握的,一点都不能急躁!
一、socket连接流程:
对于程序员来说,开始的时候只会把socket编程当成一个工具,尽快上手,尽快解决战斗。于是乎最关心的就是socket那些函数的调用顺序,那就先给出UDP/TCP的流程图(从《UNIX网络编程》)吧:
有了流程图,再找一些资料,就很容易写出下面这样的代码(以TCP为例):
服务器程序:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <unistd.h> 5 #include <sys/types.h> 6 #include <sys/socket.h> 7 #include <netinet/in.h> 8 #include <arpa/inet.h> 9 10 #define PORT 1234 11 #define BACKLOG 5 12 #define MAXDATASIZE 1000 13 14 int main() 15 { 16 int listenfd, connectfd; 17 struct sockaddr_in server; 18 struct sockaddr_in client; 19 socklen_t addrlen; 20 char szbuf[MAXDATASIZE] = {0}; 21 22 if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) 23 { 24 perror("Creating socket failed."); 25 exit(1); 26 } 27 28 bzero(&server, sizeof(server)); 29 server.sin_family = AF_INET; 30 server.sin_port = htons(PORT); 31 server.sin_addr.s_addr = htonl(INADDR_ANY); 32 if (bind(listenfd, (struct sockaddr *)&server, 33 sizeof (server)) == -1) 34 { 35 perror("Bind()error."); 36 exit(1); 37 } 38 if (listen(listenfd, BACKLOG) == -1) 39 { 40 perror("listen()error "); 41 exit(1); 42 } 43 44 addrlen = sizeof(client); 45 if ((connectfd = accept(listenfd, 46 (struct sockaddr*)&client, &addrlen)) == -1) 47 { 48 perror("accept()error "); 49 exit(1); 50 } 51 printf("You got a connection from cient's ip is %s, 52 prot is %d ", inet_ntoa(client.sin_addr), 53 htons(client.sin_port)); 54 55 memset(szbuf, 'a', sizeof(szbuf)); 56 while (1) 57 { 58 send(connectfd, szbuf, sizeof(szbuf), 0); 59 } 60 61 close(connectfd); 62 close(listenfd); 63 64 return 0; 65 }
客户端程序:
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <unistd.h> 4 #include <string.h> 5 #include <sys/types.h> 6 #include <sys/socket.h> 7 #include <netinet/in.h> 8 #include <netdb.h> 9 10 #define PORT 1234 11 #define MAXDATASIZE 1000 12 13 int main(int argc, char *argv[]) 14 { 15 int sockfd, num; 16 char buf[MAXDATASIZE + 1] = {0}; 17 struct sockaddr_in server; 18 19 if (argc != 2) 20 { 21 printf("Usage:%s <IP Address> ", argv[0]); 22 exit(1); 23 } 24 25 if ((sockfd=socket(AF_INET, SOCK_STREAM, 0)) == -1) 26 { 27 printf("socket()error "); 28 exit(1); 29 } 30 bzero(&server, sizeof(server)); 31 server.sin_family = AF_INET; 32 server.sin_port = htons(PORT); 33 server.sin_addr.s_addr = inet_addr(argv[1]); 34 if (connect(sockfd, (struct sockaddr *)&server, 35 sizeof(server)) == -1) 36 { 37 printf("connect()error "); 38 exit(1); 39 } 40 41 while (1) 42 { 43 memset(buf, 0, sizeof(buf)); 44 if ((num = recv(sockfd, buf, MAXDATASIZE,0)) == -1) 45 { 46 printf("recv() error "); 47 exit(1); 48 } 49 buf[num - 1]='