- 论坛徽章:
- 0
|
给大家两个ip地址转换函数
再接再励,总结一下,附完整代码:
/***********************************************/
#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>;
/* 根据struct sockaddr或者struct sockaddr_in得到字符串ip地址 */
char *addr_to_string(void *addr, char *ip_str);
/* 设置struct sockaddr或者struct sockaddr_in的ip地址 */
unsigned long string_to_addr(void *addr, const char *ip);
/* 根据struct sockaddr或者struct sockaddr_in得到主机子序端口号 */
unsigned short get_port_number(void *addr);
/* 设置struct sockaddr或者struct sockaddr_in的端口号 */
unsigned short set_port_number(void *addr, unsigned short port);
/* 设置struct sockaddr或者struct sockaddr_in的ip地址和端口号 */
int set_addr(void *addr, const char *ip, unsigned short port);
/* 测试程序 */
int main(int argc, char **argv)
{
char *ip = "192.168.3.1";
char vsip[16];
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
memset(vsip, 0, 16);
if(set_addr(&addr, ip, 9124) < 0)
{
printf("set_addr error!\n" ;
return -1;
}
printf("ip:%s\n", addr_to_string(&addr, vsip));
printf("port:%d\n", get_port_number(&addr));
return 0;
}
/* 根据struct sockaddr或者struct sockaddr_in得到字符串ip地址 */
char *addr_to_string(void *addr, char *ip_str)
{
unsigned char *p = NULL;
struct sockaddr_in *sin = NULL;
if(ip_str == NULL)
{
return NULL;
}
sin = (struct sockaddr_in *)addr;
if(sin == NULL)
{
return NULL;
}
p = (char *)&sin->;sin_addr;
sprintf(ip_str, "%d.%d.%d.%d", *p, *(p+1), *(p+2), *(p+3));
return ip_str;
}
/* 设置struct sockaddr或者struct sockaddr_in的ip地址 */
unsigned long string_to_addr(void *addr, const char *ip)
{
struct sockaddr_in *sin = NULL;
sin = (struct sockaddr_in *)addr;
if(sin == NULL)
{
return 0;
}
if(ip == NULL)
{
return 0;
}
sin->;sin_addr.s_addr = inet_addr(ip);
return sin->;sin_addr.s_addr;
}
/* 根据struct sockaddr或者struct sockaddr_in得到主机子序端口号 */
unsigned short get_port_number(void *addr)
{
unsigned short port = 0;
struct sockaddr_in *sin = NULL;
sin = (struct sockaddr_in *)addr;
if(sin == NULL)
{
return 0;
}
port = ntohs(sin->;sin_port);
return port;
}
/* 设置struct sockaddr或者struct sockaddr_in的端口号 */
unsigned short set_port_number(void *addr, unsigned short port)
{
struct sockaddr_in *sin = NULL;
sin = (struct sockaddr_in *)addr;
if(sin == NULL)
{
return 0;
}
sin->;sin_port = htons(port);
return sin->;sin_port;
}
/* 设置struct sockaddr或者struct sockaddr_in的ip地址和端口号 */
int set_addr(void *addr, const char *ip, unsigned short port)
{
int ret = -1;
struct sockaddr_in *sin = NULL;
sin = (struct sockaddr_in *)addr;
if(sin == NULL)
{
return ret;
}
if(ip == NULL)
{
return ret;
}
sin->;sin_addr.s_addr = inet_addr(ip);
if(sin->;sin_addr.s_addr == INADDR_NONE)
{
return ret;
}
sin->;sin_port = htons(port);
if(sin->;sin_port >; 0)
{
ret = 1;
}
return ret;
} |
|