获取本地IP地址2

来源:互联网 发布:caffe windows github 编辑:程序博客网 时间:2024/05/23 20:41
程序功能:
本程序主要获取本地的IP地址
思路分析:程序通过发送广播包,然后接受广播包,来获取IP地址和端口号

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netdb.h>
#define PORT 7778
#define MAXDATASIZE 1024
int main()
{
struct sockaddr_in user_addr,my_addr;
char my_ip[13];
int socket_fd;
int so_broadcast=1;
char buf[MAXDATASIZE];
char revbuf[MAXDATASIZE];
socklen_t size;
my_addr.sin_family=AF_INET;
my_addr.sin_port=htons(PORT);
my_addr.sin_addr.s_addr=inet_addr("255.255.255.255");
user_addr.sin_family=AF_INET;
user_addr.sin_port=htons(PORT);
user_addr.sin_addr.s_addr=htonl(INADDR_ANY);
if((socket_fd=(socket(AF_INET,SOCK_DGRAM,0)))==-1) {
perror("socket");
exit(1);
}
setsockopt(socket_fd,SOL_SOCKET,SO_BROADCAST,&so_broadcast,sizeof(so_broadcast));//socket发送的数据具有广播特性
if((bind(socket_fd,(struct sockaddr *)&user_addr, sizeof(struct sockaddr)))==-1) {
perror("bind");
exit(1);
}
strcpy(buf,"broadcast test");
sendto(socket_fd,buf,strlen(buf),0,(struct sockaddr *)&my_addr,sizeof(my_addr));
printf("buf=%s\n",buf);
printf("s_ip:%s\n",inet_ntoa(my_addr_addr.sin_addr));
printf("s_port:%d\n",ntohs(my_addr_addr.sin_port));
size=sizeof(user_addr);
recvfrom(socket_fd,buf,MAXDATASIZE,0,(struct sockaddr *)&user_addr,&size);


printf("revbuf=%s\n"revbuf);
strcpy(my_ip,inet_ntoa(user_addr.sin_addr));
printf("my_ip:%s\n",inet_ntoa(user_addr.sin_addr));
printf("my_port:%d\n",ntohs(user_addr.sin_port));
}

运行结果:

原创粉丝点击