标签:
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <string.h> #include <unistd.h> #define LEN 128 int main(int argc, const char *argv[]) { int sockfd; struct sockaddr_in serveraddr; char buf[LEN]; if(argc != 3) { fprintf(stderr, "Usage:%s serverip port.\n", argv[0]); return -1; } sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd < 0) { perror("fail to socket"); } serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = inet_addr(argv[1]); serveraddr.sin_port = htons(atoi(argv[2])); if(connect(sockfd, (struct sockaddr*)&serveraddr,sizeof(struct sockaddr)) < 0) { perror("connect failed."); return -1; } while(1) { printf("input > "); fgets(buf, LEN, stdin); if(send(sockfd, buf, sizeof(buf), 0) < 0) { perror("fail to send"); return -1; } if(strncmp(buf,"quit", 4) == 0) { break; } if(recv(sockfd, buf, sizeof(buf), 0) < 0) { perror("fail to recv"); return -1; } printf("buf:%s\n", buf); } close(sockfd); return 0; }
标签:
原文地址:http://www.cnblogs.com/otaku-lip/p/4764944.html