.net 关于获取IP地址的问题,高手帮忙看看。
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了.net 关于获取IP地址的问题,高手帮忙看看。相关的知识,希望对你有一定的参考价值。
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.htmlControls;
using System.Net;
using System.IO;
using System.Text;
public partial class admin_ip : System.Web.UI.Page
protected void Page_Load(object sender, EventArgs e)
Label1.Text=GetIP();//Label1为label的id号
// C# IP地址转长整数
public long ip2long(String ip)
System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse(ip);
byte[] bytes = ipaddress.GetAddressBytes();
Array.Reverse(bytes);
return BitConverter.ToUInt32(bytes, 0);
static string GetIP()
string strUrl = "http://www.ip138.com/ip2city.asp"; //获得IP的网址
Uri uri = new Uri(strUrl);
WebRequest wr = WebRequest.Create(uri);
Stream s = wr.GetResponse().GetResponseStream();
StreamReader sr = new StreamReader(s, Encoding.Default);
string all = sr.ReadToEnd(); //读取网站的数据
int i = all.IndexOf("[") + 1;
string tempip = all.Substring(i, 15);
string ip = tempip.Replace("]", "").Replace(" ", "");
return ip;
我用一段这样的代码来获取IP地址并显示在lable控件上,但是有个问题,我只能获取到服务器的IP,不能获取打开这个网页机器的IP地址!我不要获取服务器的IP地址。要获取打开这个网页机器的IP,求高手解答。。。。。
Response.Write(GetIP());
lable=GetIP();
访客ip:
Response.Write(HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]);
这样的写法是不考虑代理的情况的 参考技术A 中,or通常用于否定句,and用于肯定句。但有时and 也可用于否定句。请注意其不同特点: 参考技术B 注意基本的语法,语法基础
(高分)关于 gethostbyname函数的具体使用 谢谢
gethostbyname这个函数..具体要怎么用啊- -
打个比方..
比如我把www.baidu.com放到sndBuf里面..然后希望利用gethostbyname得到sndbuf里面网址的IP..要怎么搞- -..后面要用到这个IP..这个IP会放到哪- -麻烦高手帮忙下...就比如说 你在后面把这个IP打印吧-- 谢谢了!5555555
..兄弟能不能补充点啊- -
我不知道用完了gethostbyname..怎么去用我得到的IP地址..
比如下面这段程序
hptr = gethostbyname(sndBuf) ;
/* socket DLL初始化 */
WSAStartup(MAKEWORD(2, 0), &wsaData);
stSvrAddrIn.sin_family = AF_INET;
stSvrAddrIn.sin_port = htons(80);
stSvrAddrIn.sin_addr.s_addr = inet_addr("XXXXXXXXXXX");
程序中XXXXXXX就是要用gethostbyname得到的IP地址...要怎么用啊 放什么进去 谢谢
使用这个东西,首先要包含2个头文件:
#include <netdb.h>
#include <sys/socket.h>
struct hostent *gethostbyname(const char *name);
这个函数的传入值是域名或者主机名,例如"www.google.com","wpc"等等。
传出值,是一个hostent的结构(如下)。如果函数调用失败,将返回NULL。
struct hostent
char *h_name;
char **h_aliases;
int h_addrtype;
int h_length;
char **h_addr_list;
;
解释一下这个结构, 其中:
char *h_name 表示的是主机的规范名。例如www.google.com的规范名其实是www.l.google.com。
char **h_aliases 表示的是主机的别名。www.google.com就是google他自己的别名。有的时候,有的主机可能有好几个别名,这些,其实都是为了易于用户记忆而为自己的网站多取的名字。
int h_addrtype 表示的是主机ip地址的类型,到底是ipv4(AF_INET),还是ipv6(AF_INET6)
int h_length 表示的是主机ip地址的长度
int **h_addr_lisst 表示的是主机的ip地址,注意,这个是以网络字节序存储的。千万不要直接用printf带%s参数来打这个东西,会有问题的哇。所以到真正需要打印出这个IP的话,需要调用inet_ntop()。
const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) :
这个函数,是将类型为af的网络地址结构src,转换成主机序的字符串形式,存放在长度为cnt的字符串中。
这个函数,其实就是返回指向dst的一个指针。如果函数调用错误,返回值是NULL。
下面是例程,有详细的注释。
#include <netdb.h>
#include <sys/socket.h>
int main(int argc, char **argv)
char *ptr,**pptr;
struct hostent *hptr;
char str[32];
/* 取得命令后第一个参数,即要解析的域名或主机名 */
ptr = argv[1];
/* 调用gethostbyname()。调用结果都存在hptr中 */
if( (hptr = gethostbyname(ptr) ) == NULL )
printf("gethostbyname error for host:%s\n", ptr);
return 0; /* 如果调用gethostbyname发生错误,返回1 */
/* 将主机的规范名打出来 */
printf("official hostname:%s\n",hptr->h_name);
/* 主机可能有多个别名,将所有别名分别打出来 */
for(pptr = hptr->h_aliases; *pptr != NULL; pptr++)
printf(" alias:%s\n",*pptr);
/* 根据地址类型,将地址打出来 */
switch(hptr->h_addrtype)
case AF_INET:
case AF_INET6:
pptr=hptr->h_addr_list;
/* 将刚才得到的所有地址都打出来。其中调用了inet_ntop()函数 */
for(;*pptr!=NULL;pptr++)
printf(" address:%s\n", inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str)));
break;
default:
printf("unknown address type\n");
break;
return 0;
参考技术A GETHOSTBYNAME(3) Linux Programmer's Manual GETHOSTBYNAME(3)
NAME
gethostbyname, gethostbyaddr, sethostent, gethostent, endhostent,
h_errno, herror, hstrerror, gethostbyaddr_r, gethostbyname2, gethostby-
name2_r, gethostbyname_r, gethostent_r - get network host entry
SYNOPSIS
#include <netdb.h>
extern int h_errno;
struct hostent *gethostbyname(const char *name);
#include <sys/socket.h> /* for AF_INET */
struct hostent *gethostbyaddr(const void *addr,
socklen_t len, int type);
void sethostent(int stayopen);
void endhostent(void);
void herror(const char *s);
const char *hstrerror(int err);
/* System V/POSIX extension */
struct hostent *gethostent(void);
/* GNU extensions */
struct hostent *gethostbyname2(const char *name, int af);
int gethostent_r(
struct hostent *ret, char *buf, size_t buflen,
struct hostent **result, int *h_errnop);
int gethostbyaddr_r(const void *addr, socklen_t len, int type,
struct hostent *ret, char *buf, size_t buflen,
struct hostent **result, int *h_errnop);
int gethostbyname_r(const char *name,
struct hostent *ret, char *buf, size_t buflen,
struct hostent **result, int *h_errnop);
int gethostbyname2_r(const char *name, int af,
struct hostent *ret, char *buf, size_t buflen,
struct hostent **result, int *h_errnop);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
gethostbyname2(), gethostent_r(), gethostbyaddr_r(), gethostbyname_r(),
gethostbyname2_r(): _BSD_SOURCE || _SVID_SOURCE
DESCRIPTION
These functions are obsolete. Applications should use getaddrinfo(3)
and getnameinfo(3) instead.
The gethostbyname() function returns a structure of type hostent for
the given host name. Here name is either a host name, or an IPv4
address in standard dot notation (as for inet_addr(3)), or an IPv6
address in colon (and possibly dot) notation. (See RFC 1884 for the
description of IPv6 addresses.) If name is an IPv4 or IPv6 address, no
lookup is performed and gethostbyname() simply copies name into the
h_name field and its struct in_addr equivalent into the h_addr_list[0]
field of the returned hostent structure. If name doesn't end in a dot
and the environment variable HOSTALIASES is set, the alias file pointed
to by HOSTALIASES will first be searched for name (see hostname(7) for
the file format). The current domain and its parents are searched
unless name ends in a dot.
The gethostbyaddr() function returns a structure of type hostent for
the given host address addr of length len and address type type. Valid
address types are AF_INET and AF_INET6. The host address argument is a
pointer to a struct of a type depending on the address type, for exam-
ple a struct in_addr * (probably obtained via a call to inet_addr(3))
for address type AF_INET.
The sethostent() function specifies, if stayopen is true (1), that a
connected TCP socket should be used for the name server queries and
that the connection should remain open during successive queries. Oth-
erwise, name server queries will use UDP datagrams.
The endhostent() function ends the use of a TCP connection for name
server queries.
The (obsolete) herror() function prints the error message associated
with the current value of h_errno on stderr.
The (obsolete) hstrerror() function takes an error number (typically
h_errno) and returns the corresponding message string.
The domain name queries carried out by gethostbyname() and gethost-
byaddr() use a combination of any or all of the name server named(8), a
broken out line from /etc/hosts, and the Network Information Service
(NIS or YP), depending upon the contents of the order line in
/etc/host.conf. The default action is to query named(8), followed by
/etc/hosts.
The hostent structure is defined in <netdb.h> as follows:
struct hostent
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
#define h_addr h_addr_list[0] /* for backward compatibility */
The members of the hostent structure are:
h_name The official name of the host.
h_aliases
An array of alternative names for the host, terminated by a NULL
pointer.
h_addrtype
The type of address; always AF_INET or AF_INET6 at present.
h_length
The length of the address in bytes.
h_addr_list
An array of pointers to network addresses for the host (in net-
work byte order), terminated by a NULL pointer.
h_addr The first address in h_addr_list for backward compatibility.
RETURN VALUE
The gethostbyname() and gethostbyaddr() functions return the hostent
structure or a NULL pointer if an error occurs. On error, the h_errno
variable holds an error number. When non-NULL, the return value may
point at static data, see the notes below.
ERRORS
The variable h_errno can have the following values:
HOST_NOT_FOUND
The specified host is unknown.
NO_ADDRESS or NO_DATA
The requested name is valid but does not have an IP address.
NO_RECOVERY
A non-recoverable name server error occurred.
TRY_AGAIN
A temporary error occurred on an authoritative name server. Try
again later.
FILES
/etc/host.conf
resolver configuration file
/etc/hosts
host database file
/etc/nsswitch.conf
name service switch configuration
CONFORMING TO
POSIX.1-2001 specifies gethostbyname(), gethostbyaddr(), sethostent(),
endhostent(), gethostent(), and h_errno.
NOTES
The functions gethostbyname() and gethostbyaddr() may return pointers
to static data, which may be overwritten by later calls. Copying the
struct hostent does not suffice, since it contains pointers; a deep
copy is required.
In the original BSD implementation the len argument of gethostbyname()
was an int. The SUSv2 standard is buggy and declares the len parameter
of gethostbyaddr() to be of type size_t. (That is wrong, because it
has to be int, and size_t is not. POSIX.1-2001 makes it socklen_t,
which is OK.) See also accept(2).
The BSD prototype for gethostbyaddr() uses const char * for the first
argument.
POSIX.1-2001 marks gethostbyaddr() and gethostbyname() obsolescent.
See getaddrinfo(3), getnameinfo(3), gai_strerror(3).
System V/POSIX Extension
POSIX requires the gethostent() call, that should return the next entry
in the host data base. When using DNS/BIND this does not make much
sense, but it may be reasonable if the host data base is a file that
can be read line by line. On many systems a routine of this name reads
from the file /etc/hosts. It may be available only when the library
was built without DNS support. The glibc version will ignore ipv6
entries. This function is not reentrant, and glibc adds a reentrant
version gethostent_r().
GNU Extensions
Glibc2 also has a gethostbyname2() that works like gethostbyname(), but
permits to specify the address family to which the address must belong.
Glibc2 also has reentrant versions gethostent_r(), gethostbyaddr_r(),
gethostbyname_r() and gethostbyname2_r(). The caller supplies a
hostent structure ret which will be filled in on success, and a tempo-
rary work buffer buf of size buflen. After the call, result will point
to the result on success. In case of an error or if no entry is found
result will be NULL. The functions return 0 on success and a non-zero
error number on failure. In addition to the errors returned by the
non-reentrant versions of these functions, if buf is too small, the
functions will return ERANGE, and the call should be retried with a
larger buffer. The global variable h_errno is not modified, but the
address of a variable in which to store error numbers is passed in
h_errnop.
BUGS
gethostbyname() does not recognize components of a dotted IPv4 address
string that are expressed in hexadecimal.
SEE ALSO
getaddrinfo(3), getnameinfo(3), inet(3), inet_ntop(3), inet_pton(3),
resolver(3), hosts(5), nsswitch.conf(5), hostname(7), named(8)
COLOPHON
This page is part of release 3.01 of the Linux man-pages project. A
description of the project, and information about reporting bugs, can
be found at http://www.kernel.org/doc/man-pages/.
2008-06-19 GETHOSTBYNAME(3) 参考技术B 完整程序。MS VC++ 编译器:
/* =====================================*
* get_host.cpp
* get host by name and by address
* local machine may use ipconfig /all
* L_o_o_n_i_e 2008-Jun-16
* =====================================*/
#include <stdio.h>
#include <afxsock.h>
// #include <Winsock.h>
int main (int argc, char **argv)
struct hostent *he;
struct in_addr *a;
int id,i,len,flag_ip=1;
WSADATA wsa;
WORD wVersionRequested;
struct sockaddr whereto;
struct hostent *hp;
struct sockaddr_in *to;
char *target;
char *hostname, *hostIP;
if (argc != 2)
fprintf(stderr, "usage: %s life.baidu.com\n", argv[0]);
fprintf(stderr, "usage: %s 123.456.11.124\n", argv[0]);
fprintf(stderr, "for localhost: ipconfig /all\n", argv[0]);
return 1;
;
target = argv[1];
len = strlen(target);
for (i=0;i<len;i++)
if (target[i] < 0x2e || target[i] > 0x39) flag_ip=0;
wVersionRequested = MAKEWORD( 2, 0 );
if (WSAStartup(wVersionRequested , &wsa)!=0)
printf("Winsock Initialization failed.\n"); exit(0);
;
if (flag_ip == 1)
a=(struct in_addr*)malloc(sizeof(struct in_addr));
a->s_addr = inet_addr(target);
printf("looking for %s\n",target);
hp = gethostbyaddr((char *) a,4,AF_INET);
if (hp)
printf("host name:\t%s\n", hp->h_name);
printf("addtype:\t%d\n", hp->h_addrtype);
printf("length:\t\t%d\n", hp->h_length);
printf("addr_list0:\t%s\n", hp->h_addr_list[0]+hp->h_length);
while (*hp->h_aliases) printf("alias name:\t%s\n", *hp->h_aliases++);
printf("IP address: %s\n",inet_ntoa (*(struct in_addr *)*hp->h_addr_list));
else printf("can not gethostbyaddr\n"); exit(0);;
;
memset(&whereto, 0, sizeof(struct sockaddr));
to = (struct sockaddr_in *)&whereto;
to->sin_family = AF_INET;
to->sin_addr.s_addr = inet_addr(target);
if (to->sin_addr.s_addr != -1)
hostname = target;
else
if (flag_ip != 1)
hp = gethostbyname(target);
if (!hp)
printf("unknown host %s\n", target);
else
to->sin_family = hp->h_addrtype;
memcpy(&(to->sin_addr.s_addr), hp->h_addr, hp->h_length);
hostname = hp->h_name;
printf("host name:\t%s\n",hostname);
printf("addtype:\t%d\n", hp->h_addrtype);
printf("length:\t\t%d\n", hp->h_length);
while (*hp->h_aliases) printf("alias name:\t%s\n", *hp->h_aliases++);
hostIP = inet_ntoa (*(struct in_addr *)*hp->h_addr_list);
printf("host IP:\t%s\n",hostIP);
if ( flag_ip != 1 && (he = gethostbyname (argv[1])) ==NULL)
id = WSAGetLastError();
switch (id)
case WSANOTINITIALISED: printf("not initialized\n"); break;
case WSASYSNOTREADY: printf("sub sys not ready\n"); break;
case WSAHOST_NOT_FOUND: printf("name server not found\n"); break;
case WSATRY_AGAIN: printf("server fail\n"); break;
case WSANO_RECOVERY: printf("no recovery\n"); break;
case WSAEINPROGRESS: printf("socket blocked by other prog\n"); break;
case WSANO_DATA: printf("no data record\n"); break;
case WSAEINTR: printf("blocking call canciled\n"); break;
// case WSAVERNOTSUPPORTED: printf("not support\n"); break;
case WSAEPROCLIM: printf("limit exceeded\n");
case WSAEFAULT: printf("lpWSAData in startup not valid\n");
default: printf("unknown error id = %d\n",id); break;
;
;
return 0;
本回答被提问者采纳 参考技术C 注释:
gethostbyname()返回对应于给定主机名的包含主机名字和地址信息的hostent结构指针。结构的声明与gethostaddr()中一致。
返回的指针指向一个由Windows Sockets实现分配的结构。应用程序不应该试图修改这个结构或者释放它的任何部分。此外,每一线程仅有一份这个结构的拷贝,所以应用程序应该在发出其他Windows Scokets API调用前,把自己所需的信息拷贝下来。
gethostbyname()实现没有必要识别传送给它的IP地址串。对于这样的请求,应该把IP地址串当作一个未知主机名同样处理。如果应用程序有 IP地址串需要处理,它应该使用inet_addr()函数把地址串转换为IP地址,然后调用gethostbyaddr()来得到hostent结构。
返回值:
如果没有错误发生,gethostbyname()返回如上所述的一个指向hostent结构的指针,否则,返回一个空指针。应用程序可以通过WSAGetLastError()来得到一个特定的错误代码。
错误代码:
WSANOTINTIALISED 在应用这个API前,必须成功地调用WSAStartup()。
WSAENTDOWN Windows Sockets实现检测到了网络子系统的错误。
WSAHOST_NOT_FOUND 没有找到授权应答主机。
WSATRY_AGAIN 没有找到非授权主机,或者SERVERFAIL。
WSANO_RECOVERY 无法恢复的错误,FORMERR,REFUSED,NOTIMP。
WSANO_DATA 有效的名字,但没有关于请求类型的数据记录。
WSAEINPROGRESS 一个阻塞的Windows Sockets操作正在进行。
WSAEINTR 阻塞调用被WSACancelBlockingCall()取消了.
gethostbyaddr: 返回机器名称。
gethostbyname: 返回IP 网址。
作用是反的.
一个是ip换域名,
一个是域名换ip,
以上是关于.net 关于获取IP地址的问题,高手帮忙看看。的主要内容,如果未能解决你的问题,请参考以下文章
关于linux下使用s3c6410开发板实现lcd驱动的问题,高手来帮忙看看代码,看看每个函数实现啥功能
DHCP编程高手帮忙,在分配地址前加一段功能,检测非DHCP 客户机使用的IP