93 lines
1.6 KiB
C
93 lines
1.6 KiB
C
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <string.h>
|
||
|
|
||
|
#include <sys/types.h>
|
||
|
#include <sys/socket.h>
|
||
|
#include <netinet/in.h>
|
||
|
#include <arpa/inet.h>
|
||
|
|
||
|
int parse_sockaddr(const char *addr, struct sockaddr_in *sa)
|
||
|
{
|
||
|
char *buf = strdup(addr);
|
||
|
if (buf == NULL)
|
||
|
return -1;
|
||
|
|
||
|
char *tmp;
|
||
|
char *ipstr = strtok_r(buf, ":", &tmp);
|
||
|
if (ipstr == NULL) {
|
||
|
free(buf);
|
||
|
return -2;
|
||
|
}
|
||
|
|
||
|
sa->sin_family = AF_INET;
|
||
|
if (inet_pton(AF_INET, ipstr, &sa->sin_addr) <= 0) {
|
||
|
free(buf);
|
||
|
return -3;
|
||
|
}
|
||
|
|
||
|
char *portstr = strtok_r(NULL, " \r\n", &tmp);
|
||
|
if (portstr == NULL) {
|
||
|
free(buf);
|
||
|
return -4;
|
||
|
}
|
||
|
|
||
|
int port = atoi(portstr);
|
||
|
if (port < 0 || port > 65535) {
|
||
|
free(buf);
|
||
|
return -5;
|
||
|
}
|
||
|
|
||
|
sa->sin_port = htons(port);
|
||
|
free(buf);
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
int parse_subnet(const char *addr, struct in_addr *net, struct in_addr *mask)
|
||
|
{
|
||
|
char *buf = strdup(addr);
|
||
|
if (buf == NULL)
|
||
|
return -1;
|
||
|
|
||
|
char *tmp;
|
||
|
char *netstr = strtok_r(buf, "/", &tmp);
|
||
|
if (netstr == NULL) {
|
||
|
free(buf);
|
||
|
return -2;
|
||
|
}
|
||
|
|
||
|
if (inet_pton(AF_INET, netstr, net) <= 0) {
|
||
|
free(buf);
|
||
|
return -3;
|
||
|
}
|
||
|
|
||
|
char *maskstr = strtok_r(NULL, " \r\n", &tmp);
|
||
|
if (maskstr == NULL) {
|
||
|
mask->s_addr = ~0;
|
||
|
|
||
|
} else if (inet_pton(AF_INET, maskstr, mask) <= 0) {
|
||
|
int maskbits = atoi(maskstr);
|
||
|
if (maskbits < 0 || maskbits > 32) {
|
||
|
free(buf);
|
||
|
return -4;
|
||
|
}
|
||
|
|
||
|
mask->s_addr = htonl(~0 << (32 - maskbits));
|
||
|
}
|
||
|
|
||
|
free(buf);
|
||
|
return 0;
|
||
|
}
|
||
|
|
||
|
int get_sockaddr(char *buf, int size, struct sockaddr_in *addr)
|
||
|
{
|
||
|
return snprintf(buf, size, "%s:%d", inet_ntoa(addr->sin_addr), ntohs(addr->sin_port));
|
||
|
}
|
||
|
|
||
|
char * get_sockaddr_buf(struct sockaddr_in *addr)
|
||
|
{
|
||
|
static char ret[24];
|
||
|
get_sockaddr(ret, sizeof(ret), addr);
|
||
|
return ret;
|
||
|
}
|