MES3.0はLinuxの下位互換性であり、MES3.0のユーザープログラムは原則としてLinuxでも同じソースコードで動作します。
以下、MES3.0で動作確認されたLinuxとソースコード互換の有効なネットワークインターフェース一覧表示の例です。
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
#include <errno.h>
#define MAX_IFR 8
static int ifstatus(int sk, char *name) {
char buf[INET_ADDRSTRLEN + 1];
struct ifreq ifr;
struct sockaddr_in *s_in;
strncpy(ifr.ifr_name, name, IFNAMSIZ-1);
ifr.ifr_addr.sa_family = AF_INET;
ioctl(sk, SIOCGIFFLAGS, &ifr);
if(ifr.ifr_flags & IFF_UP) {
s_in = (struct sockaddr_in *)&ifr.ifr_addr;
s_in->sin_family = AF_INET;
ioctl(sk, SIOCGIFADDR, &ifr);
inet_ntop(AF_INET, &s_in->sin_addr.s_addr, buf, INET_ADDRSTRLEN);
printf("%s:\tinet %s", ifr.ifr_name, buf);
ioctl(sk, SIOCGIFNETMASK, &ifr);
inet_ntop(AF_INET, &s_in->sin_addr.s_addr, buf, INET_ADDRSTRLEN);
printf(" netmask %s", buf);
ioctl(sk, SIOCGIFHWADDR, &ifr);
printf(" ether %.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",
(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]);
}
}
static int ifdown(int sk, char *name) {
struct ifreq ifr;
struct sockaddr_in *s_in;
strncpy(ifr.ifr_name, name, IFNAMSIZ-1);
ifr.ifr_addr.sa_family = AF_INET;
ioctl(sk, SIOCGIFFLAGS, &ifr);
ifr.ifr_flags &= ~IFF_UP;
ioctl(sk, SIOCSIFFLAGS, &ifr);
return 0;
}
static int ifup(int sk, char *name, char *addr, char *mask) {
int ret;
struct ifreq ifr;
struct sockaddr_in *s_in;
strncpy(ifr.ifr_name, name, IFNAMSIZ-1);
ret = ioctl(sk, SIOCGIFFLAGS, &ifr);
if(ret == -1) {
perror("error");
return -1;
}
ifr.ifr_flags |= IFF_UP;
ioctl(sk, SIOCSIFFLAGS, &ifr);
s_in = (struct sockaddr_in *)&ifr.ifr_addr;
s_in->sin_family = AF_INET;
s_in->sin_addr.s_addr = inet_addr(addr);
ioctl(sk, SIOCSIFADDR, &ifr);
s_in->sin_addr.s_addr = inet_addr(mask);
ioctl(sk, SIOCSIFNETMASK, &ifr);
return 0;
}
int main(int argc, char **argv) {
int sk, ret, nifs, i;
struct ifreq ifrs[MAX_IFR];
struct ifconf ifc;
sk = socket(AF_INET, SOCK_DGRAM, 0);
if(sk == -1) {
perror("error");
return -1;
}
if(argc == 1) {
ifc.ifc_len = sizeof(ifrs);
ifc.ifc_ifcu.ifcu_buf = (void *)ifrs;
ioctl(sk, SIOCGIFCONF, &ifc);
nifs = ifc.ifc_len / sizeof(struct ifreq);
for(i = 0;i < nifs;i++) {
ifstatus(sk, ifrs[i].ifr_name);
}
} else if(argc == 2) {
ifstatus(sk, argv[1]);
} else if(argc == 3) {
if(strcmp(argv[2], "down") == 0) {
ifdown(sk, argv[1]);
} else {
ifup(sk, argv[1], argv[2], "255.255.255.0");
}
ifstatus(sk, argv[1]);
} else if(argc == 4) {
ifup(sk, argv[1], argv[2], argv[3]);
ifstatus(sk, argv[1]);
}
close(sk);
return 0;
}