#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <errno.h> #include <netdb.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/types.h> #include <sys/wait.h> typedef struct sockaddr SA; int open_clientfd(char* hostname,int port) { int clientfd; struct hostent * hp; struct sockaddr_in serveraddr; char* msg; /*创建socket*/ if((clientfd=socket(AF_INET,SOCK_STREAM,0))<0) { msg="client socket() error!\n"; write(STDOUT_FILENO,msg,strlen(msg)); return -1; } msg="client socket() success!\n"; write(STDOUT_FILENO,msg,strlen(msg)); /*填写server的ip地址和port*/ if((hp=gethostbyname(hostname))==NULL) { msg="client gethostbyname() error!\n"; write(STDOUT_FILENO,msg,strlen(msg)); return -2; } msg="client gethostbyname() success!\n"; write(STDOUT_FILENO,msg,strlen(msg)); bzero((char*)&serveraddr,sizeof(serveraddr)); serveraddr.sin_family=AF_INET; serveraddr.sin_port=htons(port); bcopy((char*)hp->h_addr_list[0],(char*)&serveraddr.sin_addr.s_addr,hp->h_length); /*建立连接*/ if(connect(clientfd,(SA*)&serveraddr,sizeof(serveraddr))<0) { msg="client connect() error!\n"; write(STDOUT_FILENO,msg,strlen(msg)); return -3; } msg="client connect() success!\n"; write(STDOUT_FILENO,msg,strlen(msg)); return clientfd; } int open_listenfd(int port) { int listenfd,optval; struct sockaddr_in serveraddr; char* msg; /*创建socket*/ if((listenfd=socket(AF_INET,SOCK_STREAM,0))<0) { msg="server socket() error!\n"; write(STDOUT_FILENO,msg,strlen(msg)); return -1; } msg="server socket() success!\n"; write(STDOUT_FILENO,msg,strlen(msg)); /*配置服务器使得它能被立即终止和重启*/ if(setsockopt(listenfd,SOL_SOCKET,SO_REUSEADDR,(const void *)&optval,sizeof(int))<0) { msg="server setsockopt() error!\n"; write(STDOUT_FILENO,msg,strlen(msg)); return -2; } msg="server setsockopt() success!\n"; write(STDOUT_FILENO,msg,strlen(msg)); /*绑定服务端的ip和端口*/ bzero((char*)&serveraddr,sizeof(serveraddr)); serveraddr.sin_family=AF_INET; serveraddr.sin_port=htons((unsigned short)port); serveraddr.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(listenfd,(SA*)&serveraddr,sizeof(serveraddr))<0) { msg="server bind() error!\n"; write(STDOUT_FILENO,msg,strlen(msg)); return -3; } msg="server bind() success!\n"; write(STDOUT_FILENO,msg,strlen(msg)); /*创建listen*/ if(listen(listenfd,1024)<0) { msg="server listen() error!\n"; write(STDOUT_FILENO,msg,strlen(msg)); return -3; } msg="server listen() success!\n"; write(STDOUT_FILENO,msg,strlen(msg)); return listenfd; }