connect to remote server using sockets unix - sockets

In unix, I want to make a client program connect to a server running on different machine. For this, I need to enter the ip address of server through keyboard and then pass that ip address in the connect() system call of client. I tried reading as a string, and passing it.But it didnt work. Is there any specific way to pass the ip address?

Assuming IPv4, the function you're looking for is inet_addr, which converts the string representation of an IPv4 address to a numerical value which can be passed into various socket functions:
int get_connection(const char *ip, int port)
{
int sock;
struct sockaddr_in sin;
bzero(&sin,sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(ip);
sin.sin_port = htons(port);
if ((sock=socket(AF_INET,SOCK_STREAM,0))==-1) {
perror("Error creating socket");
return -1;
}
if (connect(sock,(struct sockaddr *)&sin,sizeof(sin))==-1) {
perror("Couldn't connect");
close(sock);
return -1;
}
return sock;
}

Related

TCP simple client for a robot server. Not sending data

I am writing a simple TCP client so that I can connect to an UR (Universal Robot) robot, and send messages (popup XXXX) to the port number 29999, to generate popup messages in the UR screen. UR server does not respond correctly to the gethostbyaddr neither gethostbyname functions when connecting, so, for testing, I connect directly to the IP and Port. The code of the simple TCP client is as follows:
int initTCPSocket(void)
{
struct in_addr ip;
struct hostent *server;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
printf("ERROR opening socket");
return -1;
}
portno = atoi(serverPort.c_str());
if (!inet_aton(serverIP.c_str(), &ip))
printf(" ERROR: error parsing IP address %s", serverIP.c_str());
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htons(ip.s_addr);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
{
printf("ERROR connecting to server");
return -3;
}
else
printf("Connected to server");
}
The code that actually sends data is:
bool SendDataTCP (tekniker_tcp_comms::SendDataTCP::Request &req, tekniker_tcp_comms::SendDataTCP::Response &res)
{
if (sockfd < 0)
{
ROS_INFO("ERROR in connection");
res.dataSent=false;
return true;
}
size_t msgLength = req.msg.data.length();
//write to connected server.
int n = write(sockfd, req.msg.data.c_str(),(int)msgLength);
if (n < 0)
{
ROS_INFO("ERROR writing to socket");
res.dataSent=false;
}
else
{
ROS_INFO("write %d bytes. Message %s",n, req.msg.data.c_str());
res.dataSent=true;
}
return true;
}
I obtain messages of correct connection, and I can call the Service, and the write function works ok, but, no popup appears in the UR. It seems the UR does not receive correctly the messages.
Connecting to the UR server for popup messages using ncat ( ncat 172.16.205.2 29999) and sending messages manually works fine.
After debugging for some hours, I can not find any cause for this problem. I would appreciate a lot any kind of advise,
Thank you in advance,
After inserting Wireshark to monitor TCP/IP, the problem was with the LF termination character, that was not correctly sent.
Solving this problem the client has worked correctly.

Winsock TCP connection, send fine but recv firewall blocked

I have an application that sends a GET request using winsock on port 80 using a TCP socket. A few users have reported an issue where no response is received, looking at network logs and seeing the network device is getting the data just the app isn't it was clear that the firewall was blocking it.
Having disabled the firewall it then worked fine but what I don't understand is why it was getting blocked. The connection is created from the users computer, it connects fine and sends (which I assumes automatically opens a port) so how can data be lost on the same connection when received? Should I be providing additional winsock settings? Or is there simply no way around stopping the firewall blocking an already active connection?
Here is a stripped down version of the winsock code
SOCKET sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (sock == INVALID_SOCKET)
return -1;
struct sockaddr_in client;
memset(&client, 0, sizeof(client));
client.sin_family = AF_INET;
client.sin_port = htons(80);
client.sin_addr.s_addr = inet_addr(inet_ntoa(*addr_list[0]));
if (connect(sock, (struct sockaddr *)&client, sizeof(client)) < 0){
closesocket(sock);
return -1;
}
if (send(sock, buffer, buflength, 0) != buflength){
closesocket(sock);
return -1;
}
//get response
response = "";
int resp_leng = BUFFERSIZE;
while (resp_leng == BUFFERSIZE)
{
resp_leng = recv(sock, (char*)&buffer, BUFFERSIZE, 0);
if (resp_leng > 0)
response += std::string(buffer).substr(0, resp_leng);
else
return -1;
}
closesocket(sock);
Your while loop exits if a recv() returns less than BUFFERSIZE. This is wrong -- you must always assume that recv() can return any amount of data from 1 byte up to and including the supplied buffer size.

How to get IP used by sendto function?

When the sender has multiple network cards, this function sendto chooses random ip to send the packet.
So get the ip address used by sendto?
Code:
fd = socket(AF_INET, SOCK_DGRAM, 0);
sendto(fd, buf, len, 0, (struct sockaddr*)&servaddr, sizeof(servaddr));
It doesn't choose a random IP. It uses the OS's routing table to decide which local IP has the best chance of routing the data to the destination address. However, there is no way to query which IP sendto() actually chose to use. You could access the OS's routing table directly and try to figure it out manually, but the better option is to just bind() the socket to the specific IP that you want sendto() to use as the sending IP, eg:
fd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in localaddr;
memset(&localaddr, 0, sizeof(localaddr));
localaddr.sin_family = AF_INET;
localaddr.sin_addr.s_addr = inet_addr("192.168.0.1"); // the desired local IP
bind(fd, (struct sockaddr*)&localaddr, sizeof(localaddr));
sendto(fd, buf, len, 0, (struct sockaddr*)&servaddr, sizeof(servaddr));

ios - Determine if a certain address with a certain port is reachable

I want to know if my server is online via my ios application. Here's what I'm doing:
Boolean result;
CFHostRef hostRef = CFHostCreateWithName(kCFAllocatorDefault, (__bridge CFDataRef)(serverIPAddress)); //serverIPAdress = "10.10.10.100:5010"
if(hostRef) {
result = CFHostStartInfoResolution(hostRef, kCFHostAddresses, NULL); // pass an error instead of NULL here to find out why it failed
}
if (!result) { //This means that the host was unreachable
return ;
}
My server is online and I can access it later on in the code(meaning that my connection to the server works perfectly fine). However, I want to be able to detect if my server, on a certain port, is reachable.
Also, if I remove the ":5010" from the ip address, it detects that my server is online (it doesn't go in the "!result" condition) and detects that my server is offline if I put "10.10.10.253" which corresponds to no ip address on my network.
How can I manage to determine if my server is online or not ?
I've looked at this question : Reachability with Address - Server AND Port - iOS 5 but it doesn't work since it always return that it is reachable no matter what ip address I enter
Thanks in advance
One approach could be to open a socket connection to a specific port to see if you get any response back. If not, then the destination is unreachable. For example
#include <arpa/inet.h> //for PF_INET, SOCK_STREAM, IPPROTO_TCP etc
CFRunLoopSourceRef gSocketSource;
void ConnectCallBack(CFSocketRef socket, CFSocketCallBackType type, CFDataRef address, const void *data, void *info)
{
UInt8 buffer[1024];
bzero(buffer, sizeof(buffer));
CFSocketNativeHandle sock = CFSocketGetNative(socket); // The native socket, used recv()
//check here for correct connect output from server
recv(sock, buffer, sizeof(buffer), 0);
printf("Output: %s\n", buffer);
if (gSocketSource)
{
CFRunLoopRef currentRunLoop = CFRunLoopGetCurrent();
if (CFRunLoopContainsSource(currentRunLoop, gSocketSource, kCFRunLoopDefaultMode))
{
CFRunLoopRemoveSource(currentRunLoop, gSocketSource, kCFRunLoopDefaultMode);
}
CFRelease(gSocketSource);
}
if (socket) //close socket
{
if (CFSocketIsValid(socket))
{
CFSocketInvalidate(socket);
}
CFRelease(socket);
}
}
void ConnectSocket()
{
//socket
CFSocketContext context = {0, NULL, NULL, NULL, NULL};
CFSocketRef theSocket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketConnectCallBack , (CFSocketCallBack)ConnectCallBack, &context);
//address
struct sockaddr_in socketAddress;
memset(&socketAddress, 0, sizeof(socketAddress));
socketAddress.sin_len = sizeof(socketAddress);
socketAddress.sin_family = AF_INET;
socketAddress.sin_port = htons(5010);
socketAddress.sin_addr.s_addr = inet_addr("10.10.10.253");
gSocketSource = CFSocketCreateRunLoopSource(kCFAllocatorDefault, theSocket, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), gSocketSource, kCFRunLoopDefaultMode);
CFDataRef socketData = CFDataCreate(kCFAllocatorDefault, (const UInt8 *)&socketAddress, sizeof(socketAddress));
CFSocketError status = CFSocketConnectToAddress(theSocket, socketData, 30); //30 second timeout
//check status here
CFRelease(socketData);
}
Basically, if the server is unreachable at that port, you will most likely get a kCFSocketTimeout for CFSocketError status. If you are looking to parse a specific response back from the server to determine if the server is ready or not, the ConnectCallBack function will be called upon successful socket connection.
This is just a simple example, make sure not to block the UI by calling socket connections on the main thread such as recv()

gethostbyaddr() has error 11001

I'm writing simple program to communicate between smart devices and I receive 11001 when calling gethostbyaddr(). Both devices show they are connected to the same network, but from msdn document 11001 error is Host not found. No such host is known. Does anybody have any suggestion, thanks? My code is below.
void InitializeSocket()
{
WORD socketVersion;
WSADATA wsaData;
SOCKADDR_IN serverInfo;
int returnVal;
LPHOSTENT remotHost;
socketVersion = MAKEWORD(2,2);
WSAStartup(socketVersion, &wsaData);
in_addr iaHost;
//iaHost.s_addr = inet_addr("120.15.22.14");
iaHost.S_un.S_un_b.s_b1 = 120;
iaHost.S_un.S_un_b.s_b2 = 15;
iaHost.S_un.S_un_b.s_b3 = 22;
iaHost.S_un.S_un_b.s_b4 = 14;
remotHost = gethostbyaddr((const char *)&iaHost, sizeof(struct in_addr),
AF_INET);
if(iaHost.s_addr == INADDR_NONE)
{
MessageBox(NULL, TEXT("inet_addr has invalid address"),
TEXT("inet_addr"), MB_OK);
WSACleanup();
closesocket(theSocket);
return;
}
if(!remotHost)
{
returnVal = WSAGetLastError();
WSACleanup();
closesocket(theSocket);
return;
}
theSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(theSocket == INVALID_SOCKET)
{
returnVal = WSAGetLastError();
WSACleanup();
closesocket(theSocket);
return;
}
serverInfo.sin_family = AF_INET;
serverInfo.sin_addr = *((LPIN_ADDR)*remotHost->h_addr_list);
serverInfo.sin_port = htons(8888);
//Connect to the server
returnVal = connect(theSocket, (LPSOCKADDR)&serverInfo,
sizeof(struct sockaddr));
if(returnVal == SOCKET_ERROR)
{
returnVal = WSAGetLastError();
WSACleanup();
closesocket(theSocket);
return;
}
}
Error 11001 is a generic DNS lookup error so I have only one question. Does the 120.15.22.14 address actually exist in DNS?
You can find this out by typing
nslookup 120.15.22.14
from the command line.
If you get an error, it's because DNS doesn't know anything about those addresses, so a gethostbyaddr() will not be able to give you any information.
Update:
Answering your points:
I just type nslookup 120.15.22.14, but it returns back as cant find 120.15.22.14. Non-existent domain.
Since nslookup 120.15.22.14 returns an error, there is no entry in DNS for that IP address. That's your problem.
I look at my device settings for the DNS and it sets to 120.20.32.10 which is different 120.15.22.14 so does it mean I haven't configured the DNS?
If 120.20.32.10 is what's in DNS for your device, and 120.15.22.14 is the actual address, then DNS is wrong. Plain and simple. Fix DNS.
will it produce the same result if I use gethostbyname() instead of gethostbyaddr()?
If you want to turn a DNS name into an IP address, use gethostbyname(). To turn an IP address into a DNS name, use gethostbyaddr().
For connecting to a remote host, you would normally use the gethostbyname() call since the IP address of the host could change at any time. Provided DNS always accurately represents the IP address of that host, that's the preferred way.
I just type nslookup 120.15.22.14, but it returns back as cant find 120.15.22.14. Non-existent domain.
I look at my device settings for the DNS and it sets to 120.20.32.10 which is different 120.15.22.14 so does it mean I haven't configured the DNS?