代码作业

服务器连接代码

#include"stdio.h"
#include"sys/types.h"
#include"sys/socket.h"
#include"stdlib.h"
#include"sys/un.h"

#include"arpa/inet.h"
#include"string.h"
#define PORT 33333
#define MAX_SIZE 1024

int main()
{
 int sockfd;
 int cfd;
 int c_len;
 int opt=1;
 char buffer[MAX_SIZE];

 struct sockaddr_in addr;
 struct sockaddr_in c_addr;
 struct sockaddr_in s_addr;

 sockfd = socket(AF_INET,SOCK_STREAM,0);
 if(sockfd==-1)
 {
  perror("socket create fail\n");
  exit(1);
 }
 printf("socket success!\n");

 bzero(&addr,sizeof(struct sockaddr_in));
 addr.sin_family = AF_INET;
 addr.sin_port =htons(PORT);
 addr.sin_addr.s_addr=inet_addr("192.168.253.134");

 setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));

 bzero(&s_addr,sizeof(struct sockaddr_in));
 s_addr.sin_family = AF_INET;
 s_addr.sin_port=htons(PORT);
 s_addr.sin_addr.s_addr=inet_addr("192.168.253.134");

 if( bind(sockfd,(struct sockaddr *)(&s_addr),sizeof(struct sockaddr_in))<0)
  {
    perror("bind fail\n");
    exit(1);
  }
  printf("bind success!\n");

 if( listen(sockfd,3)<0)
 {
  perror("listen error\n");
  exit(1);
 }
 printf("listen success!\n");

 while(1)
{

 //memset(buffer,0,sizeof(buffer));

 bzero(&c_addr,sizeof(struct sockaddr_in));
 c_len=sizeof(struct sockaddr_in);

 printf("accepting......\n");
    
 cfd= accept(sockfd,(struct sockaddr *)(&c_addr),&c_len);
 if(cfd < 0)
 {
    perror("accept error!\n");
    exit(1);
 }
 //read(cfd,buffer,sizeof(buffer));

 //printf("recv = %s\n",buffer);

 printf("port = %d ip = %s\n",ntohs(c_addr.sin_port),inet_ntoa(c_addr.sin_addr));
 usleep(2);

 //write(cfd,buffer,strlen(buffer));


}
 return 0;

}

客户端连接代码


 #include"stdio.h"
   #include"string.h"
   
   #include"sys/types.h"
   #include"sys/socket.h"
   #include"arpa/inet.h"
   
   #define PORT 33333
  
  int main()
  {
    int sockfd;
    struct sockaddr_in s_addr;
    if((sockfd = socket(AF_INET,SOCK_STREAM,0))<0)
    {
      perror("client socket success!\n");
      exit(1);
    }
  
    printf("client socket success!\n");

    bzero(&s_addr,sizeof(struct sockaddr_in));
    s_addr.sin_family = AF_INET;
    s_addr.sin_port = htons(PORT);
    s_addr.sin_addr.s_addr = inet_addr("192.168.253.134");
 
    if(connect(sockfd,(struct sockaddr *)(&s_addr),sizeof(struct sockaddr_in))<0)
    {
      perror("connect error!\n");
      exit(1);
    }
    
    printf("connect!\n");
    //write(sockfd,"hello world",12);
    return 0;
  } 

你可能感兴趣的:(代码作业)