/* TCP Echo Client Author :Andrew Huang
*/
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h>
#include <stdio.h> #include <string.h>
int main(int argc ,char * argv[]) { unsigned short port = 9000; int sock ; char ipaddr[32] = "127.0.0.1"; char buf[32] = "hello server"; struct sockaddr_in serv_addr; int len;
if(argc >1) { port = (unsigned short)atoi(argv[1]); }
if(argc >2) { memset(ipaddr,0,sizeof(ipaddr)); strncpy(ipaddr,argv[2],sizeof(ipaddr)-1); }
if(argc > 3) { memset(buf,0,sizeof(buf)); strncpy(buf,argv[3],sizeof(buf)-1); }
printf("connect server %s:%d,buf %s\n",ipaddr,port,buf);
//第一步:创建一个IPV4,TCP,可以运行所有协议的SOCKET
sock = socket(PF_INET,SOCK_STREAM,0); if(sock == -1) { perror("socket"); return -1; }
//第二步:对于客户端,port可用任意一个编号,如果不使用bind,协议栈会自动分配没用的端口0
// 省略bind ....
//第三步:用connect()去联接服务器
memset(&serv_addr,0,sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(port); serv_addr.sin_addr.s_addr = inet_addr(ipaddr); //printf("ipaddr %s,s_addr %x\n",ipaddr,ntohl( serv_addr.sin_addr.s_addr));
if(connect(sock,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) == -1) { perror("connect"); close(sock); return -2; } #if 1 /* socket扩展 */ {//可以从socket取到自己所绑定的端口和地址
socklen_t addr_len; memset(&serv_addr ,0 ,sizeof(serv_addr)); addr_len = sizeof(serv_addr); getsockname(sock,(struct sockaddr *)&serv_addr,&addr_len); fprintf(stdout,"local addr %s ,port %d\n",inet_ntoa(serv_addr.sin_addr),ntohs(serv_addr.sin_port));
//扩展3:使用getpeername,根据socket查出对端的地址的端口.
memset(&serv_addr ,0 ,sizeof(serv_addr)); addr_len = sizeof(serv_addr); getpeername(sock,(struct sockaddr *)&serv_addr,&addr_len); fprintf(stdout,"peer addr %s ,port %d\n",inet_ntoa(serv_addr.sin_addr),ntohs(serv_addr.sin_port));
}
#endif if(send(sock,buf,strlen(buf)+1,0)<= 0) { perror("send"); close(sock); return -3; }
len = recv(sock,buf,sizeof(buf),0); if(len >0) { buf[len] = 0; printf("SERVER:%s\n",buf); }
//关闭socket
close(sock); }
|