LinuxÍø¿¨µÄ¶Áд±à³Ìzz
LinuxϵͳµÄËùÓÐÉ豸¶¼ÊÇÒÔÎļþµÄÐÎʽ´æÔڵģ¬ËùÒÔ¶ÔϵͳµÄ²Ù×÷¿ÉÒÔת»»Îª¶ÔÎļþµÄ²Ù×÷¡£±¾³ÌÐòʵÏÖ¶ÔÍø¿¨Õâ¸öÓ²¼þÉ豸½øÐжÁÈ¡²Ù×÷£¬¼´Ò²ÊǶÔÉ豸µÄÎļþ½øÐжÁд²Ù×÷¡£´úÂë¿´ËÆÂé·³£¬µ«È´²»¸´ÔÓ¡£
Ö÷ÒªµÄϵͳº¯ÊýÓУºsocket(),ioctl(),memcpy(),strcpy()¡£
Á½¸ö¸´ÔӵĽṹÌ壺sockaddr_in,ifreq¡£
...£¯
#include<stdio.h>
#include<unistd.h>
#include<sys/ioctl.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<net/if.h>
#include<string.h>
unsigned char g_eth_name[16];
unsigned char g_macaddr[6];
unsigned char g_ipaddr;
unsigned char g_subnetmask;
unsigned char g_broadcast_ipaddr;
void init_net(void)
{
int i;
int sock;
struct sockaddr_in sin;
struct ifreq ifr;
sock=socket(AF_INET,SOCK_DGRAM,0);
if(sock==-1)
printf("get the socket file descriptor faild!\n");
strcpy(g_eth_name,"etho");
strcpy(ifr.ifr_name,g_eth_name);
strcpy("eth name:\t%s\n",g_eth_name);
if(ioctl(sock,SIOCGIFHWADDR,&ifr)<0)
printf("get the network card addr faild!\n");
memcpy(g_macaddr,ifr.ifr_hwaddr.sa_data,6);
printf("the network card addr is:");
for(i=0;i<5;i++)
printf("%.2x:",g_macaddr[i]);
printf("%.2x:",g_macaddr[i]);
if(ioctl(sock,SIOCGIFADDR,&ifr)<0)
printf("get the net ip addr faild!\n");
memcpy(&sin,&ifr.ifr_addr,sizeof(sin));
g_ipaddr=sin.sin_addr.s_addr;
printf("local eth0:\t%s\n",inet_ntoa(sin.sin_addr));
if(ioctl(sock,SIOCGIFBRDADDR,&ifr)<0)
printf("get the broadcast ip addr faild!\n");
memcpy(&sin,&ifr.ifr_addr,sizeof(sin));
g_broadcast_ipaddr=sin.sin_addr.s_addr;
printf("broadcast:\t%s\n",inet_ntoa(sin.sin_addr));
if(ioctl(sock,SIOCGIFNETMASK,&ifr)<0)
printf("get the netsubmask faild!\n");
memcpy(&sin,&ifr.ifr_addr,sizeof(sin));
g_subnetmask=sin.sin_addr.s_addr;
printf("subnetmask:\t%s\n",inet_ntoa(sin.sin_addr));
close(sock);
}
int main()
{
init_ne