Open C Networking and Sockets |
In Linux, the function ioctl() is used to get the user's own IP address. But on mobile devices, an IP address is not always allotted. It is assigned as and when a connection is established and will be relinquished when the connection is terminated and/or no other connection exists. (GPRS is assumed as bearer connection)
It is important to know that on mobiledevices, ioctl() returns the access point name rather than the IP address. So the alternative way to get the mobile IP is using Symbian RSocket.
The following example illustrates this. The example code tries to connect to www.nokia.com (147.243.3.83). If this server is down, change it to any other server. Look at the output , the "My IP" might change every time this application is executed. To get a constant IP on successive executions, run the browser and connect to some site, for example www.nokia.com and search in the background.
#include <stdio.h> #include <es_sock.h> #include <in_sock.h> #include <unistd.h> const TUint32 KInetAddrServ = INET_ADDR(147,243,3,83); const TInt KServPort = 80; int main() { RSocket fd; TRequestStatus status = KRequestPending; TInetAddr recvAddr; TInt retval; RSocketServ iRSockServ; /* Connecting to the socket server */ retval = iRSockServ.Connect(); if(retval != KErrNone) { printf("Error : Connecting to the socket server !!\n"); User::Leave(KErrGeneral); } /* Opening a socket */ retval = fd.Open(iRSockServ, KAfInet, KSockStream, KProtocolInetTcp); if(retval != KErrNone) { printf("ERROR : Socket not created !!\n"); User::Leave( KErrGeneral); } else { printf("INFO : Socket created... \n"); } /* Connecting a socket */ TInetAddr servAddr(KInetAddrServ, KServPort); fd.Connect(servAddr,status); User::WaitForRequest(status); printf ("INFO: Socket Connected..\n"); /* Getting info */ TInetAddr myaddr, remoteaddr; fd.LocalName(myaddr); fd.RemoteName(remoteaddr); TUint32 myIP = myaddr.Address(); TUint32 remoteIP = remoteaddr.Address(); printf("MY IP = %x or %d.%d.%d.%d\n",myIP, ((myIP >> 24) & 0xff), ((myIP >> 16) & 0xff), ((myIP >> 8) & 0xff), ((myIP >> 0) & 0xff)); printf("Remote IP = %x or %d.%d.%d.%d\n",remoteIP, ((remoteIP >> 24) & 0xff), ((remoteIP >> 16) & 0xff), ((remoteIP >> 8) & 0xff), ((remoteIP >> 0) & 0xff)); printf ("Sleeping for 10 sec...before exit\n"); sleep(10); }
©Nokia 2007 |