TCP/IPサーバー・デーモンを作成していると、PORTの使用有無を検査したい場合がある。
通常は、PORTの使用を検査できないものと考えられがちであるが、
実はこれを可能にする方法がある。
以下にそのソースを紹介する。
これは実際に EnterpriseServer で使用されているソースである。
0001.00 /********************************************************************/
0002.00 /* */
0003.00 /* PORTCHK : PORT 検査 */
0004.00 /* */
0005.00 /* Office Quattro Co,.Ltd 2005/9/16 10:44:20 created */
0006.00 /* */
0007.00 /********************************************************************/
0008.00 #include <stdio.h>
0009.00 #include <stdlib.h>
0010.00 #include <string.h>
0011.00 #include <netdb.h>
0012.00 #include <sys/types.h>
0013.00 #include <sys/socket.h>
0014.00 #include <netinet/in.h>
0015.00 #include <netinet/tcp.h>
0016.00 #include <arpa/inet.h>
0017.00
0018.00 #define TRUE 0
0019.00 #define FALSE -1
0020.00 #define SERV_HOST_ADDR "127.0.0.1"
0021.00 #define MAXPORT 1024
0022.00 #define BUFLEN 1024
0023.00 #define SBUFLEN 256
0024.00
0025.00 /***********************/
0026.00 /* 関数の定義 */
0027.00 /***********************/
0028.00
0029.00 /********************************************************************/
0030.00 /* m a i n --- main module of this pgm */
0031.00 /*------------------------------------------------------------------*/
0032.00 /* Parameter : 1. PORT[4] */
0033.00 /* 2. RESULT[4] */
0034.00 /* */
0035.00 /********************************************************************/
0036.00 void main(int argc, char *argv[]){
0037.00 struct sockaddr_in addr;
0038.00 struct servent *sent;
0039.00 int fd, i, j, rtn, n;
0040.00 char buf[BUFLEN];
0041.00 int PORT;
0042.00 char result[6];
0043.00
0044.00 /*[ パラメータの取得 ]*/
0045.00 PORT = atoi(argv[1]);
0046.00 /* ソケットの準備 */
0047.00 fd = socket(AF_INET, SOCK_STREAM, 0);
0048.00 memset((char*)&addr, 0, sizeof(addr));
0049.00 addr.sin_family = AF_INET;
0050.00 addr.sin_addr.s_addr = inet_addr(SERV_HOST_ADDR);
0051.00 addr.sin_port = htons((short)PORT);
0052.00
0053.00 memset(result, 0, sizeof(result));
0054.00 /* サーバーと接続 */
0055.00 if((rtn = connect(fd, (struct sockaddr *)&addr, sizeof(addr))) ==
0056.00 memcpy(result, "FALSE", 5);
0057.00 }
0058.00 else memcpy(result, "TRUE ", 5);
0059.00 close(fd);
0060.00 memcpy(argv[2], result, 5);
0061.00 exit(0);
0062.00
0063.00 }