?? socket.h
字號:
#include <sys/socket.h>#include <netinet/in.h>#include <arpa/inet.h>#include <netdb.h>#include<stdio.h>#include<string.h> char check_error[16348]={}; struct sockaddr_in pin; struct hostent *server_host_name;int socket_com(char *host_name,int port, char *str){ char buf[8192]={}; char port_exchange[10]={}; int socket_descriptor; int errorcount1=1; int errorcount2=1; int errorcount3=1; int errorcount4=1; int errorcount5=1; int export_flag=0;//resolving the host name while(errorcount1<=3) { if((server_host_name=gethostbyname(host_name))==0) errorcount1++; else break; } if(errorcount1==4) { strcpy(check_error,"Host_name:"); strcat(check_error,host_name); strcat(check_error," Port:"); sprintf(port_exchange,"%d",port); strcat(check_error,port_exchange); strcat(check_error,": Error resolving local host\n"); return -1; } //init the port now bzero(&pin,sizeof(pin)); pin.sin_family=AF_INET; pin.sin_addr.s_addr=htonl(INADDR_ANY); pin.sin_addr.s_addr=((struct in_addr*)(server_host_name->h_addr))->s_addr; pin.sin_port=htons(port);//create socket while(errorcount2<=3) { if((socket_descriptor=socket(AF_INET,SOCK_STREAM,0))==-1) errorcount2++; else break; } if(errorcount2==4) { strcpy(check_error,"Host_name:"); strcat(check_error,host_name); strcat(check_error," Port:"); sprintf(port_exchange,"%d",port); strcat(check_error,port_exchange); strcat(check_error,": Error create socket\n"); return -1; }//check connect while(errorcount3<=3) { if(connect(socket_descriptor,(void*)&pin,sizeof(pin))==-1) errorcount3++; else break; } if(errorcount3==4) { strcpy(check_error,"Host_name:"); strcat(check_error,host_name); strcat(check_error," Port:"); sprintf(port_exchange,"%d",port); strcat(check_error,port_exchange); strcat(check_error,": Error connecting socket\n"); return -1; }//check send while(errorcount4<=3) { if(send(socket_descriptor,str,strlen(str),0)==-1) errorcount4++; else break; } if(errorcount4==4) { strcpy(check_error,"Host_name:"); strcat(check_error,host_name); strcat(check_error," Port:"); sprintf(port_exchange,"%d",port); strcat(check_error,port_exchange); strcat(check_error,": Error in send\n"); return -1; }//check receive while(errorcount5<=3) { if(recv(socket_descriptor, buf, 8192, 0)==-1) errorcount5++; else break; } if(errorcount5==4) { strcpy(check_error,"Host_name:"); strcat(check_error,host_name); strcat(check_error," Port:"); sprintf(port_exchange,"%d",port); strcat(check_error,port_exchange); strcat(check_error,": Error in receive\n"); return -1; }//check result strcpy(check_error,buf); close(socket_descriptor); return 0;}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -