79 lines
1.6 KiB
C
79 lines
1.6 KiB
C
|
#include <sys/types.h>
|
||
|
#include <sys/socket.h>
|
||
|
#include <netinet/in.h>
|
||
|
#include <arpa/inet.h>
|
||
|
#include <errno.h>
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <unistd.h>
|
||
|
|
||
|
int _valid_ipv4_port(const char *str, int port)
|
||
|
{
|
||
|
int ret;
|
||
|
int fd;
|
||
|
int i;
|
||
|
volatile int local_errno;
|
||
|
struct sockaddr_in addr;
|
||
|
fd = socket(AF_INET,SOCK_STREAM,0); //初始化socket
|
||
|
|
||
|
|
||
|
if(fd ==-1) //检查是否正常初始化socket
|
||
|
{
|
||
|
return -1;
|
||
|
}
|
||
|
|
||
|
errno = 0;
|
||
|
local_errno = errno;
|
||
|
|
||
|
ret = inet_pton(AF_INET, str ,&addr.sin_addr);
|
||
|
printf("the value of ret is:%d\n",ret);
|
||
|
if(ret > 0)
|
||
|
{
|
||
|
fprintf(stderr, "\"%s\" is a vaild IPv4 address\n", str);
|
||
|
|
||
|
addr.sin_family = AF_INET; //地址结构的协议簇
|
||
|
addr.sin_port=htons(port); //地址结构的端口地址,网络字节序
|
||
|
printf("the value of str:%s\n", str);
|
||
|
i = (bind(fd, (struct sockaddr*)&addr, sizeof(struct sockaddr)));
|
||
|
printf("the value of i:%d\n", i);
|
||
|
|
||
|
if( i < 0)
|
||
|
{
|
||
|
printf("port %d has been used. \n", port);
|
||
|
close(fd);
|
||
|
return -1;
|
||
|
}
|
||
|
|
||
|
printf("port %d is ok. \n", port);
|
||
|
close(fd);
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
else if (ret < 0)
|
||
|
{
|
||
|
fprintf(stderr, "EAFNOSUPPORT: %s\n", strerror(local_errno));
|
||
|
return -1;
|
||
|
}
|
||
|
else
|
||
|
{
|
||
|
fprintf(stderr, "\"%s\" is not a vaild IPv4 address\n", str);
|
||
|
return -1;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
|
||
|
|
||
|
int main()
|
||
|
{
|
||
|
char a[] ="192.168.209.193";
|
||
|
char *pIP = a;
|
||
|
char *pNotIP = "192.168.0.256";
|
||
|
int port = 56298;
|
||
|
int port1 = 3369;
|
||
|
_valid_ipv4_port(pIP, port);
|
||
|
_valid_ipv4_port(pIP, port1);
|
||
|
_valid_ipv4_port(pNotIP, port1);
|
||
|
|
||
|
return 0;
|
||
|
}
|