Obtain and modify the netmask subnet mask in Linux.

Source: Internet
Author: User
Tags socket connect

// Obtain the subnet mask FunctionQstring getlocalnetmask () <br/>{< br/> int sock_netmask; <br/> char netmask_addr [50]; </P> <p> struct ifreq ifr_mask; <br/> struct sockaddr_in * net_mask; </P> <p> sock_netmask = socket (af_inet, sock_stream, 0); <br/> If (sock_netmask =-1) <br/>{< br/> perror ("create socket failture... getlocalnetmask/N "); <br/> return" "; <br/>}</P> <p> memset (& ifr_mask, 0, sizeof (ifr_mask )); <br/> strncpy (signature, ifname, sizeof (ifr_mask.ifr_name)-1); </P> <p> If (IOCTL (sock_netmask, siocgifnetmask, & ifr_mask )) <0) <br/>{< br/> printf ("Mac IOCTL error/N"); <br/> return ""; <br/>}</P> <p> net_mask = (struct sockaddr_in *) & (ifr_mask.ifr_netmask); <br/> strcpy (netmask_addr, inet_ntoa (net_mask-> sin_addr); </P> <p> printf ("Local netmask: % s/n", netmask_addr ); </P> <p> close (sock_netmask); <br/> return qstring (netmask_addr); <br/>}

// Modify the subnetmask Function

Qstring setlocalnetmask (const char * sznetmask) <br/>{< br/> int sock_netmask; <br/> char netmask_addr [32]; </P> <p> struct ifreq ifr_mask; <br/> struct sockaddr_in * sin_net_mask; </P> <p> sock_netmask = socket (af_inet, sock_stream, 0 ); <br/> If (sock_netmask =-1) <br/> {<br/> perror ("not create network socket connect/N "); <br/> return ""; <br/>}</P> <p> memset (& ifr_mask, 0, sizeof (ifr_mask )); <br/> strncpy (ifr_mask.ifr_name, "eth0", sizeof (ifr_mask.ifr_name)-1); <br/> sin_net_mask = (struct sockaddr_in *) & signature; <br/> sin_net_mask-> sin_family = af_inet; <br/> inet_pton (af_inet, sznetmask, & sin_net_mask-> sin_addr ); </P> <p> If (IOCTL (sock_netmask, siocsifnetmask, & ifr_mask) <0) <br/>{< br/> printf ("sock_netmask IOCTL error/N"); <br/> return "; <br/>}< br/>}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.