/* ============================================================================ Name : TCPclient.c Author : vestinfo Version : 1.1 Copyright : www.cnblogs.com/vestinfo Description : TCP client ============================================================================ */ #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <stdio.h> #include <sys/stat.h> #include <fcntl.h> #define PORT 8888 #define REMOTE_IP "127.0.0.1" #define CLIENT_PORT 9999 #define CLIENT_IP "192.168.77.172" #define MAXLENGTH 256 int main() { int sockfd; struct sockaddr_in servaddr; struct sockaddr_in clientaddr; char mybuffer[MAXLENGTH]; /* 创建套接字。 */ if((sockfd = socket(AF_INET, SOCK_STREAM, 0))<0) { perror("socket"); exit(1); } /* 绑定client的地址和端口;当然client端可不绑定,由内核分配。 */ bzero(&clientaddr, sizeof(clientaddr)); clientaddr.sin_family = AF_INET; clientaddr.sin_port = htons(CLIENT_PORT); clientaddr.sin_addr.s_addr = inet_addr(CLIENT_IP); if(bind(sockfd, (struct sockaddr *)&clientaddr, sizeof(clientaddr)) < 0) { perror("bind"); exit(1); } /* 向server发起连接请求 */ bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(PORT); servaddr.sin_addr.s_addr = inet_addr(REMOTE_IP); if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))<0) { perror("connect"); exit(1); } else { printf("connected successfully!\n"); printf("remote ip:%s\n",REMOTE_IP); printf("remote port:%d\n",PORT); } for( ; ; ) { bzero(mybuffer, MAXLENGTH); read(STDIN_FILENO, mybuffer, MAXLENGTH); //从键盘读信息,STDIN_FILENO=0. if(write(sockfd, mybuffer, strlen(mybuffer)) < 0) //发送从键盘读到的信息 { perror("write"); exit(1); } if(read(sockfd, mybuffer, MAXLENGTH) <= 0) { perror("read"); close(sockfd); exit(1); } else { printf("received from server:%s\n", mybuffer); } } return 0; }