赞
踩
- #include<stdlib.h>
- #include<stdio.h>
- #include<string.h>
- #include<winsock.h>
-
- #ifdef INADDR_NONE
- #define INADDR_NONE 0xffffffff
- #endif /*INADDR_NONE*/
-
- void errexit(const char *);
- /*
- connectsock --> allocate & connect a socket using TCP or UDP
- */
-
- //host 服务器端点地址
- //service 服务名
- //transport 传输层协议
- SOCKET connectsock(const char * host,const char* service,
- const char * transport){
- struct hostent *phe; //pointer to host information entry
- struct servent *pse; //pointer to service information entry
- struct protoent *ppe; //pointer to protocal iunformation entry
- struct sockaddr_in sin; //an Internet endpoint address
- int s,type; //socket descriptor and socket type
- memset(&sin,0,sizeof(sin));
- sin.sin_family = AF_INET;
-
- //Map service name to port number
- if(pse = getservbyname(service,transport)){
- sin.sin_port = pse.s_port;
- }else if((sin.sin_port = htons((u_short)atoi(service))) == 0){
- errexit("can't get \"%s\" service entry\n",service);
- }
-
- //Map host name to IP address,allowing for dotted decimal_point
- if(phe = gethostbyname(host)){
- memcpy(&cin.sin_addr,phe->h_addr,phe->h_length);
- }else if((sin.sin_addr.s_addr = inet_addr(host)) == INADDR_NONE){
- errexit("can't get \"%s\" host entry\n",host);
- }
-
- //Map protocol name to protocal number
- if(ppe = getprotobyname(transport) == 0){
- errexit("can't get \"%s\" protocal entry\n",transport);
- }
-
- //Use protocal to choose a socket type
- if(strcmp(transport,"udp")==0){
- type = SOCK_DGRAM;
- }else{
- type = SOCK_STREAM;
- }
- //Allocate a socket
- s = socket(PF_INET,type,ppe->p_proto);
- if(s == INVALID_SOCKET){
- errexit("can't create socket:%d",GetLastError());
- }
- //Connect the socket
- if(connect(s,(struct sockaddr*)&sin,sizeof(sin)) == SOCKET_ERROR){
- errexit("can't connect to %s.%s: %d\n",host,service,GetLastError());
- }
- return s;
- }
- #include <winsock.h>
- SOCKET connectsock(const char*,const char*,const char*);
-
- //connectUDP -> connect to a specified UDP service on a specified host
- SOCKET connectUDP(const char*host,const char* service){
- return connectsock(host,service,"udp")
- }
-
- #include <winsock.h>
- SOCKET connectsock(const char*,const char*,const char*);
-
- //connectUDP -> connect to a specified UDP service on a specified host
- SOCKET connectTCP(const char*host,const char* service){
- return connectsock(host,service,"tcp")
- }
- #include<stdarg.h>
- #include<stdio.h>
- #include<stdlib.h>
- #include<winsock.h>
-
- //errexit -> print an error message and exit
-
- void errexit(const char* format){
- va_list args;
- va_start(args,format);
- vfprintf(stderr,format,args);
- va_end(args);
- WSACleanup();
- exit(1);
- }
UDP使用数据报的方式,因此每次发送和接收的数据是完整的,因此不需要使用循环,只需要一次接收即可
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。