日期:2014-05-16  浏览次数:20929 次

Unix下测试指定IP的端口是否开放

平时与不同业务之间联调的时候,经常得提前测试对方给的IP及端口是否开放着,Unix下用其它办法有点麻烦,索性用C语言自己写了一个程序。

?

?

#include <stdio.h>
#include <strings.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
//#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include <netdb.h>

#define TIMEOUT 5

/*
FileName:testConn.c
functions:test host:port which specified whether is alive.
call:testConn hostname port
return values:
0 :connected.
1:arguments err.
2:port number illegal.
3:gethostname err.
4:network setup err.
5:Connect server timeout.
*/
//Build by cc at HPUX: cc -g -Wall testConn.c -o testConn

int main(int argc, char **argv)
{
  if(argc != 3)
  {
    printf("error:Usage: %s host port.\nExample: %s 192.168.0.1 21\n",argv[0],argv[0]);
    exit(1);
  }
  
  int portnumber=0;
  if ((portnumber = atoi (argv[2])) < 0)
  {
    fprintf (stderr, "error:port number[%s] is illegal.\n", argv[0]);
    exit (2);
  }

  struct hostent *host;
  if ((host = gethostbyname (argv[1])) == NULL)
  {
    fprintf (stderr, "error:Gethostname error\n");
    exit (3);
  }

  int sockfd, flags, res;
  struct sockaddr_in servaddr;
  fd_set fdr, fdw;
  struct timeval timeout;
  
  sockfd = socket(AF_INET, SOCK_STREAM, 0);
  if(sockfd < 0) 
  {
    perror("error:Netwrok error...\n");
    return 4;
  }
  
  /* set socket fd noblock */
  if((flags = fcntl(sockfd, F_GETFL, 0)) < 0) 
  {
    perror("error:Netwrok error...\n");
    close(sockfd);
    return 4;
  }
  
  if(fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) < 0) 
  {
    perror("error:Network error...\n");
    close(sockfd);
    return 4;
  }
  
  bzero(&servaddr, sizeof(servaddr));
  servaddr.sin_family = AF_INET;
  //inet_pton(AF_INET, argv[1], &servaddr.sin_addr);
  servaddr.sin_addr = *((struct in_addr *) host->h_addr);
  servaddr.sin_port = htons(portnumber);
  
  if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) != 0) 
  {
    if(errno != EINPROGRESS) 
    { // EINPROGRESS
      perror("error:Network err....\n");
      close(sockfd);
      return 4;
    }
  }
  else 
  {
    printf("Connected\n");
    return 0;
  }
  
  FD_ZERO(&fdr);
  FD_ZERO(&fdw);
  FD_SET(sockfd, &fdr);
  FD_SET(sockfd, &fdw);
  
  timeout.tv_sec = TIMEOUT;
  timeout.tv_usec = 0;
  
  res = select(sockfd + 1, &fdr, &fdw, NULL, &timeout);
  if(res < 0) 
  {
    perror("error:Network error...\n");
    close(sockfd);
    return 4;
  }
  if(res == 0) 
  {
    printf("error:Connect server timeout\n");
    close(sockfd);
    return 5;
  }
  if(res == 1) 
  {
    if(FD_ISSET(sockfd, &fdw))
    {
      printf("Connected\n");
      close(sockfd);
      return 0;
    }
  }
  /* Not necessary */
  if(res == 2) 
  {
    printf("error:Connect server timeout\n");
    close(sockfd);
    return 5;
  }
  
  printf("error:Connect server timeout\n");
  close(sockfd);
  return 5;
}

?