unpheader.h

以后贴的程序可能会一直用这个东西,所以先贴上来,就三个函数,不自动重启被信号中断的系统调用的signal_intr,建立连接sockfd的getconnection(ip,port)和建立倾听sockfd的initlisten(port)。


#ifndef _UNP_H
#define _UNP_H
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <netdb.h>
#include <errno.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/select.h>
#include <fcntl.h>
#define MAXLINE 1024
#define RWRWRW (S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP | S_IWOTH | S_IROTH)
#define RWXRWXRWX (S_IWUSR | S_IRUSR | S_IXUSR | S_IWGRP | S_IRGRP | S_IXGRP | S_IWOTH | S_IROTH | S_IXOTH)
typedef void (*sighandler_t)(int);

sighandler_t signal_intr(int signo,sighandler_t func)
{
 struct sigaction act,oact;
 act.sa_handler = func;
 sigemptyset(&act.sa_mask);
 act.sa_flags = 0;
#ifdef SA_INTERRUPT
 act.sa_flags |= SA_INTERRUPT;
#endif
 if(sigaction(signo,&act,&oact) < 0)
  return (SIG_ERR);
 return (oact.sa_handler);
}

int initlisten(int port)
{
 int listenfd;
 struct sockaddr_in servaddr;
 if( (listenfd = socket(AF_INET,SOCK_STREAM,0))< 0)
 {
  printf("socket error! %s\n",strerror(errno));
  return -1;
 }
 bzero(&servaddr,sizeof(struct sockaddr_in));
 servaddr.sin_family = AF_INET;
 servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
 servaddr.sin_port = htons(port);
 if( -1 == (bind(listenfd,(struct sockaddr*)&servaddr,sizeof(servaddr))) )
 {
  printf("bind error! %s,%d\n",strerror(errno),port);
  return -1;
 }
 if( -1 == (listen(listenfd,1024)))
 {
  printf("listen error! %s,%d\n",strerror(errno),port);
  return -1;
 }
 return listenfd;
}

int getconnection(char *ip,int port)
{
 int sockfd,reuse=1;
 struct sockaddr_in cliaddr;
 if( (sockfd = socket(AF_INET,SOCK_STREAM,0))< 0)
 {
  printf("socket error! %s\n",strerror(errno));
  return -1;
 }
 if( setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(int)) < 0)
 {
  printf("set reuseaddr error! %s\n",strerror(errno));
  return -1;
 }
 bzero(&cliaddr,sizeof(struct sockaddr_in));
 cliaddr.sin_family = AF_INET;
 cliaddr.sin_port = htons(port);
 if ( inet_pton(AF_INET,ip,&cliaddr.sin_addr) <= 0)
 {
  printf("inet_pton error for %s,%s\n",ip,strerror(errno));
  return -1;
 }

 if(connect(sockfd,(struct sockaddr*)&cliaddr,sizeof(cliaddr)) < 0)
 {
  printf("connect error for %s\n",strerror(errno));
  return -1;
 }

 return sockfd;
}

#endif
转载请注明来源:Leoncom-《unpheader.h》
Trackback

no comment untill now

Add your comment now