in reply to Can I change the IP by perl it own

Here is how you do it in C. I would just toss this into inline C and call it a day but it would be easy enough to convert to Perl. Note SIOCDIFADDR (to delete old address) will fail and return an einvalue on Linux as it was not implemented in the (older) kernels for IPV4. It works anyway, despite the error message. If you are on BSD or other *nix flavour it should just work.....

#include <sys/types.h> #include <sys/socket.h> #include <sys/ioctl.h> #include <netinet/in.h> #include <net/if.h> #include <errno.h> int main() { char iface[] = "eth0"; char ip[] = "192.168.1.3"; IP_SetIP(iface,ip); return 0; } int IP_SetIP(const char* interface, const char * ip_address ) { int sock=0; struct sockaddr_in* addr=NULL; struct ifreq ifr; sock = socket( AF_INET, SOCK_DGRAM, 0 ); if( sock == -1 ) { printf("Can't get a socket!"); return (-1); } memset(&ifr,0,sizeof( struct ifreq ) ); strncpy(ifr.ifr_name,interface,IFNAMSIZ); if( ioctl( sock, SIOCGIFADDR, &ifr ) < 0 ) { printf("Can't get IP '%s' because: '%s'\n",interface,strerror( +errno)); } else { if( ioctl( sock, SIOCDIFADDR, &ifr ) < 0 ) { printf("Can't remove '%s' because: '%s'\n",interface,strer +ror(errno)); } } memset( &ifr, 0, sizeof( struct ifreq ) ); addr= (struct sockaddr_in *)&(ifr.ifr_addr); memset(addr, 0, sizeof( struct sockaddr_in) ); addr->sin_family=AF_INET; addr->sin_addr.s_addr=inet_addr(ip_address); strncpy(ifr.ifr_name,interface,IFNAMSIZ); if( ioctl( sock, SIOCSIFADDR, &ifr ) != 0 ) { printf("Can't fix IP of '%s' with '%s' because '%s'\n", interface,ip_address,strerror(errno)); close(sock); return (-1); } else { printf("IP for '%s' set to'%s'\n",interface,inet_ntoa(addr->si +n_addr)); } close(sock); return(0); }

cheers

tachyon

Replies are listed 'Best First'.
Re^2: Can I change the IP by perl it own
by A_Banknote (Initiate) on Jul 16, 2004 at 13:51 UTC
    thanks
    I'm sorry for that I igored your post and post a new post