c语言获取ip、mac、port并用字符串装起来
时间: 2023-08-04 19:05:05 浏览: 106
C语言浮点数转字符串_C语言浮点数字符串_浮点数转换_
5星 · 资源好评率100%
获取IP、MAC、Port需要使用不同的系统调用和方法,下面是一个简单的示例程序,可以获取本机IP、MAC和随机的Port,并将它们存储在字符串中:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#include <arpa/inet.h>
char* get_local_ip() {
int fd;
struct ifreq ifr;
char* ip = (char*)malloc(16);
fd = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
ioctl(fd, SIOCGIFADDR, &ifr);
close(fd);
strcpy(ip, inet_ntoa(((struct sockaddr_in*)&ifr.ifr_addr)->sin_addr));
return ip;
}
char* get_local_mac() {
int fd;
struct ifreq ifr;
unsigned char* mac = (unsigned char*)malloc(18);
fd = socket(AF_INET, SOCK_DGRAM, 0);
ifr.ifr_addr.sa_family = AF_INET;
strncpy(ifr.ifr_name, "eth0", IFNAMSIZ-1);
ioctl(fd, SIOCGIFHWADDR, &ifr);
close(fd);
sprintf(mac, "%02X:%02X:%02X:%02X:%02X:%02X",
(unsigned char)ifr.ifr_hwaddr.sa_data[0],
(unsigned char)ifr.ifr_hwaddr.sa_data[1],
(unsigned char)ifr.ifr_hwaddr.sa_data[2],
(unsigned char)ifr.ifr_hwaddr.sa_data[3],
(unsigned char)ifr.ifr_hwaddr.sa_data[4],
(unsigned char)ifr.ifr_hwaddr.sa_data[5]);
return mac;
}
int get_random_port() {
int port = rand() % 65536;
while (port <= 1024) {
port = rand() % 65536;
}
return port;
}
int main() {
char* ip = get_local_ip();
char* mac = get_local_mac();
int port = get_random_port();
char* str = (char*)malloc(50);
sprintf(str, "IP:%s, MAC:%s, Port:%d", ip, mac, port);
printf("%s\n", str);
free(ip);
free(mac);
free(str);
return 0;
}
```
注意,这个程序只是一个简单的示例,仅用于展示获取IP、MAC和Port的方法,并不是完整的实现。实际应用中,需要根据具体需求进行修改和完善。
阅读全文