通过 sockaddr_in gethostname 等将主机转换为 ip
我需要帮助将主机名转换为 ip 并插入到 sockaddr_in->sin_addr 才能分配给 char。 例如我输入:localhost,它给了我 127.0.0.1
我找到了代码,但我不知道为什么它给了我错误的数字
//---
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <time.h>
#include <sys/fcntl.h>
#include <netdb.h>
//---
///CZY WPISANO HOST
struct in_addr inaddr;
inaddr.s_addr = inet_addr(argv[1]);
if( inaddr.s_addr == INADDR_NONE) //if sHost is name and not IP
{
struct hostent* phostent = gethostbyname( argv[1]);
if( phostent == 0)
bail("gethostbyname()");
if( sizeof(inaddr) != phostent->h_length)
bail("problem z inaddr"); // error something wrong,
puts(argv[1]);
inaddr.s_addr = *((unsigned long*) phostent->h_addr);
//strdup( inet_ntoa(inaddr));
srvr_addr = inet_ntoa(adr_srvr.sin_addr);
puts(srvr_addr);
}
我也编写了自己的代码,但我不知道如何从 sockaddr 传输到 sockaddr_in 数据:
///CZY WPISANO HOST
if(argv[1][0]>=(char)'a' && argv[1][0]<=(char)'Z')
{
struct hostent *hent;
hent = gethostbyname(argv[1]);
adr_srvr.sin_addr = (struct in_addr*)hent->h_addr_list;
}
adr_srvr 是
char*
类型
I need help converting hostname to ip and inserting to sockaddr_in->sin_addr to be able assign to char.
For example I input: localhost and it gives me 127.0.0.1
I found code, but I dont know why it gives me wrong numbers
//---
#include <sys/types.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <time.h>
#include <sys/fcntl.h>
#include <netdb.h>
//---
///CZY WPISANO HOST
struct in_addr inaddr;
inaddr.s_addr = inet_addr(argv[1]);
if( inaddr.s_addr == INADDR_NONE) //if sHost is name and not IP
{
struct hostent* phostent = gethostbyname( argv[1]);
if( phostent == 0)
bail("gethostbyname()");
if( sizeof(inaddr) != phostent->h_length)
bail("problem z inaddr"); // error something wrong,
puts(argv[1]);
inaddr.s_addr = *((unsigned long*) phostent->h_addr);
//strdup( inet_ntoa(inaddr));
srvr_addr = inet_ntoa(adr_srvr.sin_addr);
puts(srvr_addr);
}
I also wrote own code but i dont know how transfer from sockaddr to sockaddr_in data:
///CZY WPISANO HOST
if(argv[1][0]>=(char)'a' && argv[1][0]<=(char)'Z')
{
struct hostent *hent;
hent = gethostbyname(argv[1]);
adr_srvr.sin_addr = (struct in_addr*)hent->h_addr_list;
}
adr_srvr
is a char*
type
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试这样的事情:
我直接从记忆中编写了这段代码,所以我不能保证它有效,但我很确定它应该没问题。
Try something like this:
I wrote this code straight from my memory so I cannot guarantee that it works but I am pretty sure it should be OK.
我相信这个 C 代码符合您的要求:
我得到的输出是这样的:
希望这会有所帮助。
This C code does I believe what you want it to:
The output I got was this:
Hope this helps.