TCP Socket编程实例1---Client端

/*
*TcpClient.c
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVPORT 1888
#define MAXDATASIZE 30
 
int main(int argc,char *argv[])
{
   int sockfd,sendbytes;
   char buf[MAXDATASIZE];
   struct hostent *host;
   struct sockaddr_in serv_addr;
   if(argc<2){
      fprintf(stderr,"Please enter the server's hostname!\n");
      exit(1);
  }
/*get host*/
  if((host=gethostbyname(argv[1]))==NULL){
    perror("gethostbyname");
    exit(1);
  }
/*Create Socket*/
  if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){
    perror("socket");
    exit(1); 
  }
 
  /*Set sockaddr_in parameters*/
  serv_addr.sin_family = AF_INET;       //地址簇
  serv_addr.sin_port = htons(SERVPORT); //端口号
  serv_addr.sin_addr = *((struct in_addr*)host->h_addr); //Sever的IP地址
  bzero(&(serv_addr.sin_zero),8);   //填充0,以保持和struct sockaddr一样大小
 
/*connect to Sever*/
if(connect(sockfd,(struct sockaddr *)&serv_addr,sizeof(struct sockaddr))==-1){
   perror("connect");
   exit(1);
}
 
/*send msg to server*/
  if((sendbytes=send(sockfd,"hello",5,0))==-1){
     perror("send");
     exit(1);
  }
 close(sockfd);
}

你可能感兴趣的:(【嵌入式开发】,【LINUX/UNIX】)