linux socket编程服务端模型(用getaddrinfo)

//server_wait.c

#include "unistd.h"
#include "sys/types.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "arpa/inet.h"
#include "stdio.h"
#include "string.h"
#include <netdb.h>
#include <stdarg.h>
#include <errno.h>
#include <sys/utsname.h>

void error(int status, int err,char *fmt, ...) {
        va_list ap;
 va_start(ap, fmt);
 vfprintf(stderr, fmt, ap);
        va_end(ap);
 if(err)
  fprintf(stderr,":%s(%d)/n",strerror(err),err);
        if(status)
    exit(status);
}
          
int  server_wait(const char *hostname,const char *service,const char *protocol){
  int sockfd,err;
  struct addrinfo hints,*res,*r;
  bzero(&hints,sizeof(struct addrinfo));
  hints.ai_family=AF_INET;
  if(strcmp(protocol,"udp")==0)
   hints.ai_socktype=SOCK_DGRAM;
  else if(strcmp(protocol,"tcp")==0)
   hints.ai_socktype=SOCK_STREAM;
  err=getaddrinfo(hostname,service,&hints,&res);
  if(err){
   printf("%s/n",gai_strerror(err));
 exit(0);
  }
  for( r = res; r; r = r->ai_next) {
   if((sockfd=socket(r->ai_family,r->ai_socktype,r->ai_protocol))<0)
  continue;
 if(bind(sockfd,r->ai_addr,r->ai_addrlen)==0)
  break;
 close(sockfd);
  }
  if(r==NULL)
   error(1,0,"error!!/n");

 if((r->ai_socktype==SOCK_STREAM)&&(listen(sockfd,5)<0))
  error(1,0,"listen error!");
 
 freeaddrinfo(res);
 return sockfd;
  }
 

//udpserver.c

#include <stdarg.h>
#include <stdio.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>

void process_server(int s) {
     struct sockaddr_in remote;
     char buff[128];
     int len,n;
     while(1){
      n=recvfrom(s,buff,sizeof(buff),0,(struct sockaddr *)&remote,&len);
 //printf("%s,%d/n",buff,n);
 buff[n]='/0';
 sendto(s,buff,strlen(buff), 0, (struct sockaddr *)&remote,sizeof(remote));
     }
}

int main(int argc, char **argv) {
    struct sockaddr_in remote;
    char *hname, *sname;
    int s, c, len;
    if(argc < 2)
     error(1,0,"parameters less than 2");
    else if(argc == 2) {
     hname = NULL;
 sname = argv[1];
    }
    else if(argc == 3) {
     hname = argv[1];
 sname = argv[2];
    }
    s = server_wait(hname, sname,"udp");
    process_server(s);
    close(s);
    exit(0);
}

你可能感兴趣的:(linux socket编程服务端模型(用getaddrinfo))