服务器端代码
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <arpa/inet.h> int main( int argc, char *argv[] ) { int sockfd, new_fd; struct sockaddr_in server_addr; struct sockaddr_in client_addr; int sin_size, portnumber; const char hello[] = "Hello!\n"; if ( argc != 2 ) { printf("Usage: %s portnumber\a\n", argv[0]); exit(1); } if ( (portnumber = atoi(argv[1])) < 0 ) { printf("Usage: %s portnumber\a\n", argv[0]); exit(1); } /* 服务器端创建socket */ if ( ( sockfd = socket(AF_INET, SOCK_STREAM, 0) ) == 1 ) { printf("Socket Error !\n"); exit(1); } /* 服务器端填充sockaddr结构 */ bzero( &server_addr, sizeof(struct sockaddr_in) ); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(portnumber); /* 将本地地址与socket绑定 */ if ( bind( sockfd, (struct sockaddr *)(&server_addr), sizeof(struct sockaddr) ) == -1 ) { printf("Bind Error!\n"); exit(1); } /* 进入监听模式 */ if ( listen( sockfd, 5 ) == 1 ) { puts("Listen Error!"); exit(1); } while (1) { /* 服务器阻塞,直到与客户端建立连接 */ sin_size = sizeof(struct sockaddr_in); if ( (new_fd = accept(sockfd, (struct sockaddr *)(&client_addr), (socklen_t *)&sin_size ) ) == -1 ) { puts("Accept Error!"); exit(1); } /* 连接成功 */ printf("Server get connection from %s\n", inet_ntoa(client_addr.sin_addr) ); inet_ntoa(client_addr.sin_addr); if ( write( new_fd, hello, strlen(hello) ) == -1 ) { puts("Write Error!"); exit(0); } /* 本次通信结束,循环下一个 */ close(new_fd); } /* 关闭当前连接 */ close(sockfd); return 0; }
客户端代码
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> #include <netdb.h> #include <sys/types.h> #include <netinet/in.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> int main( int argc, char *argv[] ) { int sockfd; char buffer[1124]; struct sockaddr_in server_addr; struct hostent *host; int portnumber, nbytes; if ( argc != 3 ) { printf("Usage: %s hostname portnumber\n", argv[0] ); exit(1); } if ( (host = gethostbyname(argv[1])) == NULL ) { puts("Host Error!"); exit(1); } if ( (portnumber = atoi(argv[2])) < 0 ) { printf("Usage: %s portnumber\a\n", argv[0]); exit(1); } if ( ( sockfd = socket(AF_INET, SOCK_STREAM, 0) ) == 1 ) { printf("Socket Error !\n"); exit(1); } bzero( &server_addr, sizeof(struct sockaddr_in) ); server_addr.sin_family = AF_INET;
server_addr.sin_port = htons( portnumber ); server_addr.sin_addr = *((struct in_addr *)host->h_addr);
/* 与服务器建立连接 */ if ( connect( sockfd, (struct sockaddr *)(&server_addr), sizeof(server_addr) ) == -1 ) { puts("Connect Error!"); exit(1); } if ( (nbytes = read(sockfd, buffer, 1024)) == -1 ) { puts("Read Error!"); exit(1); } buffer[nbytes] = '\0'; printf("I have received: %s\n", buffer ); close(sockfd); return 0; }
运行结果