易网时代-编程资源站
Welcome
微信登录
编程资源
图片资源库
蚂蚁家优选
PDF转换器
软件资源
软件开发
、
小程序制作
、
系统集成与运维
、
空间租用
、
硬件开发
、
视频监控
、
技术咨询与支持
——联系电话:0311-88999002/88999003
首页
/
操作系统
/
Linux
/
Linux网络编程:获取本机的公网IP
Linux网络编程:获取本机的公网IP
[cpp]
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <netdb.h>
#include <stddef.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#define BUF_SIZE 512
int
port = 80;
void
getip(
char
*url)
{
struct
sockaddr_in pin;
struct
hostent *nlp_host;
int
sd = 0;
int
len = 0;
int
i, count = 0;
int
recv_start = 0, recv_end = 0;
char
buf[BUF_SIZE] = { 0 }, myurl[100] =
{
0};
char
host[100] = { 0 }, GET[100] =
{
0}, header[240] =
{
0};
char
*pHost = 0;
///get the host name and the relative address from url name!!!
strcpy(myurl, url);
for
(pHost = myurl; *pHost !=
"/"
&& *pHost !=
" "
; ++pHost) ;
if
((
int
)(pHost - myurl) == strlen(myurl))
strcpy(GET,
"/"
);
else
strcpy(GET, pHost);
*pHost =
" "
;
strcpy(host, myurl);
///setting socket param
if
((nlp_host = gethostbyname(host)) == 0)
{
perror(
"error get host "
);
exit(1);
}
bzero(&pin,
sizeof
(pin));
pin.sin_family = AF_INET;
pin.sin_addr.s_addr = htonl(INADDR_ANY);
pin.sin_addr.s_addr = ((
struct
in_addr *)(nlp_host->h_addr))->s_addr;
pin.sin_port = htons(port);
if
((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror(
"Error opening socket!!! "
);
exit(1);
}
///together the request info that will be sent to web server
///Note: the blank and enter key byte is necessary,please remember!!!
strcat(header,
"GET"
);
strcat(header,
" "
);
strcat(header, GET);
strcat(header,
" "
);
strcat(header,
"HTTP/1.1 "
);
strcat(header,
"HOST:"
);
strcat(header, host);
strcat(header,
" "
);
strcat(header,
"ACCEPT:*/*"
);
strcat(header,
" Connection: close "
);
///connect to the webserver,send the header,and receive the web sourcecode
if
(connect(sd, (
void
*)&pin,
sizeof
(pin)) == -1)
printf(
"error connect to socket "
);
if
(send(sd, header, strlen(header), 0) == -1)
{
perror(
"error in send "
);
exit(1);
}
///send the message and wait the response!!!
len = recv(sd, buf, BUF_SIZE, 0);
if
(len < 0)
printf(
"receive data error!!! "
);
else
{
printf(
"%s"
, &(buf[157]));
}
close(sd);
}
int
main()
{
char
*url =
"www.3322.org/dyndns/getip"
;
getip(url);
return
0;
}
运行结果:
[root@www.linuxidc.com test]#
[root@www.linuxidc.com test]# gcc getIP.c -o getIP
[root@www.linuxidc.com test]# ./getIP
218.13.34.138
[root@www.linuxidc.com test]#
收藏该网址
版权所有©石家庄振强科技有限公司2024
冀ICP备08103738号-5
网站地图