TCP_client

廖永长
2023-12-01

#include "common.h"

int main (int argc, char *argv[])
{
 int sock_fd,conn_fd;
 struct sockaddr_in server_addr,client_addr;
 socklen_t addrlen = ADDR_SIZE;
 int wc = -1,rc = -1;
 char buffer_r[BUFFER_SIZE],buffer_w[BUFFER_SIZE];
 int con_times = 0;
 int i = 1;
 struct hostent *host;
 
 if(argc != 2)
 {
  fprintf(stderr,"Usage:%s ip\n",argv[0]);
  exit(EXIT_FAILURE);
 }
 
 sock_fd = socket(AF_INET,SOCK_STREAM,0);
 if(sock_fd == -1)
  Err_sys("Client socket:")
 
 //host = gethostbyname("localhost");
 //host = gethostbyname("localhost.localdomain");
 host = gethostbyname(argv[1]);
 
 bzero(&server_addr,ADDR_SIZE);
 server_addr.sin_family = AF_INET;
 server_addr.sin_port = htons(Server_port);
 //server_addr.sin_addr.s_addr = inet_addr("192.168.59.128");;
 server_addr.sin_addr = *((struct in_addr *)host->h_addr);
 
 
 //bzero(&client_addr,ADDR_SIZE);
 //client_addr.sin_family = AF_INET;
 //client_addr.sin_port = htons(8080);
 //client_addr.sin_addr.s_addr = inet_addr("127.0.0.1");;
 
 
 
 setsockopt(sock_fd,SOL_SOCKET,SO_REUSEADDR,(void *)&i,sizeof(i));
 
 //if(bind(sock_fd,(struct sockaddr *)&client_addr,addrlen) == -1)
 // Err_sys("Client bind:")

 while((conn_fd = connect(sock_fd,(struct sockaddr *)&server_addr,addrlen)) == -1)
 {
  if(con_times < 3)
  {
   printf("Client connecting ...........\n");
   sleep(3);
  }
  else
  {
   printf("Client connected failfully \n");
   exit(EXIT_FAILURE);
  }
  con_times++;
 } //while
 
 while(RUNNING)
 {
  memset(buffer_w,0,BUFFER_SIZE);
  printf("[Client send]:");
  fflush(stdout);
  fgets(buffer_w,BUFFER_SIZE,stdin);
  wc =  send(sock_fd,buffer_w,BUFFER_SIZE,0);
  if(wc <= 0)
   Err_sys("Client send:")
 
  memset(buffer_r,0,BUFFER_SIZE);
 
  fflush(stdout);
  rc =  recv(sock_fd,buffer_r,BUFFER_SIZE,0);
  if(rc <= 0)
   Err_sys("Client recv:")
 
  printf("[Client recv]:%s\n",buffer_r);

 } //while
 
 close(sock_fd);
 return 0;
}

 类似资料:

相关阅读

相关文章

相关问答