1 #pragma once 2 #include<stdlib.h> 3 #include<stdio.h> 4 #include<string.h> 5 #include<winsock.h> 6 7 void errexit(const char*, ...); 8 9 #ifndef INADDR_NONE 10 #define INADDR_NONE 0xfffffff 11 #endif 12 13 14 SOCKET connectsock(const char *host, const char *service, 15 const char *transport) { 16 struct hostent *phe; 17 struct servent *pse; 18 struct protoent *ppe; 19 struct sockaddr_in sin; 20 int s, type; 21 22 memset(&sin, 0, sizeof(sin)); 23 sin.sin_family = AF_INET; 24 if (pse = getservbyname(service, transport)) 25 sin.sin_port = pse->s_port; 26 else if ((sin.sin_port = htons((u_short)atoi(service))) == 0) 27 errexit("can‘t get\"%s\"service entry\n", service); 28 if (phe = gethostbyname(host)) 29 memcpy(&sin.sin_addr, phe->h_addr, phe->h_length); 30 else if ((sin.sin_port = inet_addr(host)) == INADDR_NONE) 31 errexit("can‘t get\"%s\"host entry\n", host); 32 if((ppe = getprotobyname(transport)) == 0) 33 errexit("can‘t get\"%s\"protocol entry\n", transport); 34 35 if (strcmp(transport, "udp") == 0) 36 type = SOCK_DGRAM; 37 else 38 type = SOCK_STREAM; 39 40 s = socket(PF_INET, type, ppe->p_proto); 41 if(s == INVALID_SOCKET) 42 errexit("can‘t create socket:%d\n",GetLastError()); 43 44 if(connect(s,(struct sockaddr *)&sin,sizeof(sin)) == SOCKET_ERROR) 45 errexit("can‘t connect\n", GetLastError()); 46 return s; 47 } 48 49 50 51 52 void errexit(const char *format, ...) { 53 va_list args; 54 va_start(args, format); 55 vfprintf(stderr, format, args); 56 va_end(args); 57 WSACleanup(); 58 exit(1); 59 }
1 #include<stdlib.h> 2 #include<stdio.h> 3 #include<winsock.h> 4 #include"conect.h" 5 6 void tcpdaytime(const char*, const char *); 7 void errexit(const char*, ...); 8 SOCKET connecttcp(const char*, const char *); 9 10 #define LINELEN 128 11 #define WSVERS MAKEWORD(2,0) 12 13 14 int main(int argc, char *argv[]) { 15 char *host = "localhost"; 16 char *service = "daytime"; 17 WSADATA wsadata; 18 switch (argc) { 19 case 1: 20 host = "localhost"; 21 break; 22 case 3: 23 service = argv[1];//没有break 24 case 2: 25 host = argv[1]; 26 break; 27 default: 28 fprintf(stderr, "usage:tcpdaytime[host[port]]\n"); 29 exit(1); 30 } 31 if (WSAStartup(WSVERS, &wsadata) != 0) 32 errexit("wsastartup error\n"); 33 tcpdaytime(host, service); 34 WSACleanup(); 35 return 0; 36 } 37 38 39 void tcpdaytime(const char *host, const char *service) { 40 char buf[LINELEN + 1]; 41 SOCKET s; 42 int cc; 43 s = connecttcp(host, service); 44 cc = recv(s, buf, LINELEN, 0); 45 while (cc != SOCKET_ERROR && cc > 0) { 46 buf[cc] = ‘\0‘; 47 (void)fputs(buf, stdout); 48 cc = recv(s, buf, LINELEN, 0); 49 } 50 closesocket(s); 51 } 52 53 SOCKET connecttcp(const char*host, const char *service) { 54 return connectsock(host, service, "tcp"); 55 }
时间: 2024-10-16 22:10:33