The following code is a program designed to send ICMP echo requests and receive replies.
/*
Forgive my lack of error handling :)
*/
SOCKET ASOCKET = INVALID_SOCKET;
struct sockaddr saddr;
struct sockaddr_in *to = (struct sockaddr_in *) &saddr;
struct sockaddr_in from;
int fromsize = sizeof(from);
std::string ip = "[arbitrary ip address]";
struct ICMP {
USHORT type;
USHORT code;
USHORT cksum;
USHORT id;
USHORT seq;
}*_ICMP;
char sendBuffer[sizeof(struct ICMP)];
char recvBuffer[256];
WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);
memset(&saddr, NULL, sizeof(saddr));
ASOCKET = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
// Configure timeout
DWORD timeoutmilsec = 3000;
setsockopt(ASOCKET, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeoutmilsec, sizeof(timeoutmilsec));
to->sin_family = AF_INET;
inet_pton(AF_INET, ip.c_str(), &(to->sin_addr));
_ICMP = new ICMP();
_ICMP->type = 8;
_ICMP->code = 0;
_ICMP->cksum = 0;
_ICMP->id = rand();
_ICMP->seq++;
// I have omitted my declaration of checksum() for simplicity
_ICMP->cksum = checksum((u_short *)_ICMP, sizeof(struct ICMP));
memcpy(sendBuffer, _ICMP, sizeof(struct ICMP));
if (sendto(ASOCKET, sendBuffer, sizeof(sendBuffer), NULL, (sockaddr *)&saddr, sizeof(saddr)) == SOCKET_ERROR)
{
printf("sendto() failed with error: %u\n", WSAGetLastError());
return false;
}
if (recvfrom(ASOCKET, recvBuffer, sizeof(recvBuffer), NULL, (sockaddr *)&from, &fromsize) == SOCKET_ERROR)
{
if (WSAGetLastError() == TIMEOUTERROR)
{
printf("Timed out\n\n");
return false;
}
printf("recvfrom() failed with error: %u\n", WSAGetLastError());
return false;
}
My issue is that my recvfrom() call does not receive any data and returns TIMEOUTERROR (10060) despite the fact that the ping has been replied to (Wireshark captures the request and reply being sent). sendto() works but recvfrom() behaves weirdly and I can't figure out what the problem is.
What I find interesting is recvfrom() will receive data only when the gateway tells me that a host is unreachable; it won't if the host is reachable and has responded to the ping.
The problem lies in struct ICMP.
type and code of ICMP should be unsigned char.
Header of ICMP should be 8-byte, but size of struct ICMP is 10 bytes.
So it should be changed to:
struct ICMP {
unsigned char type;
unsigned char code;
USHORT cksum;
USHORT id;
USHORT seq;
}*_ICMP;
It turns out the whole time it was my firewall blocking the responses. The only error in my code was the size of my ICMP struct (mentioned by cshu).
Thanks for all the help everyone.
Related
I am working on a C++ project that needs to establish a connection via SSH to a remote server and execute some commands and transfer files via SFTP. However, I need this application to work in dual stack mode (e.g., with IPv6 and IPv4) mode.
In the snippet below, my program initially receives an host-name, IPv6 or IPv4 address. In the IPv4 input the connection is successful. However, I am having strange problems in the IPv6 mode that I am noticing that the connection is established via socket and the SSH session fails to start.
Currently, I believe it could be something related to the inet_ntop() method. Please notice that remoteHost variable is an char* type and the remotePort is uint16_t type.
// Initialize some important variables
uint32_t hostaddr = 0, hostaddr6 = 0;
struct sockaddr_in sin = {};
struct sockaddr_in6 sinV6 = {};
int rc = 0, sock = 0, i = 0, auth_pw = 0;
// Here we will initialize our base class with username and password
this->username = usrName;
this->password = usrPassword;
// Firstly, we need to translate the hostname into an IPv4 or IPv6 address
struct addrinfo hints={}, *sAdrInfo = {};
char addrstr[100]={};
void *ptr= nullptr;
char addrParsed[50]={};
memset (&hints, 0, sizeof (hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags |= AI_CANONNAME;
// Now we need to get some address info from the one supplied that remoteHost parameter
int errcode = getaddrinfo (remoteHost, nullptr, &hints, &sAdrInfo);
if (errcode != 0) {
SERVER_ERROR("[SSH] Error while getaddrinfo at SSHConnect() code %d", errno);
return -4;
}
inet_ntop(sAdrInfo->ai_family, sAdrInfo->ai_addr->sa_data, addrstr, 100);
// Here we need to determine if we are using IPv6 or IPv4
switch (sAdrInfo->ai_family) {
case AF_INET6:
ptr = &((struct sockaddr_in6 *) sAdrInfo->ai_addr)->sin6_addr;
break;
case AF_INET:
ptr = &((struct sockaddr_in *) sAdrInfo->ai_addr)->sin_addr;
break;
}
inet_ntop(sAdrInfo->ai_family, ptr, addrstr, 100);
sprintf(addrParsed, "%s", addrstr);
//This part is responsible for creating the socket and establishing the connection
// Now if we have an IPv4 based host
if (sAdrInfo->ai_family == AF_INET) {
this->hostaddr = inet_addr(addrParsed);
sock = socket(AF_INET, SOCK_STREAM, 0);
sin.sin_family = AF_INET;
// Now we need to set these (address and port to our sockaddr_in variable sin)
sin.sin_port = htons(remotePort);
memcpy(&sin.sin_addr, &hostaddr, sizeof(hostaddr));
}
// Now if we have an IPv6 based host
else if (sAdrInfo->ai_family == AF_INET6) {
this->hostaddr6 = inet_addr(addrParsed);
sock = socket(AF_INET6, SOCK_STREAM, 0);
sin.sin_family = AF_INET6;
// Now we need to set these (address and port to our sockaddr_in variable sin)
sinV6.sin6_port = htons(remotePort);
memcpy(&sinV6.sin6_addr.s6_addr32, &hostaddr6, sizeof(this->hostaddr6));
}
// Now we need to connect to our socket :D
if (sAdrInfo->ai_family == AF_INET) {
int resCon = connect(sock, (struct sockaddr*)(&sin), sizeof(struct sockaddr_in));
if (resCon != 0){
SERVER_ERROR("[SSH] failed to connect with error code: %d!\n", errno);
return -1;
}
}
else if (sAdrInfo->ai_family == AF_INET6) {
int resCon = connect(sock, (struct sockaddr*)(&sinV6), sizeof(struct sockaddr_in6));
if (resCon != 0){
SERVER_ERROR("[SSH] failed to connect with error code: %d!\n", errno);
return -1;
}
}
// Free our result variables
freeaddrinfo(sAdrInfo);
// Create a session instance
session = libssh2_session_init();
if(!session) {
return -2;
}
/* Now to start the session. Here will trade welcome banners, exchange keys and setup crypto, compression,
* and MAC layers */
rc = libssh2_session_handshake(session, sock);
if(rc) {
SERVER_ERROR("Failure establishing SSH session: %d\n", rc);
return -3;
}
What is wrong with the implementation that is generating the "Failure establishing SSH session" message with IPv6 stack?
Best regards,
I'm trying to receive a message from the server in my client, and although I don't get any compiling errors, my buffer won't take what the server is sending. I've tried changing the parameters in recvfrom in the client to correlate to the parameters used in the client's sendto but the same thing happens, my memset buffer remains empty. I've also tried just sending a simple null terminated char array of size two to test it, and the same result occurs.
Server:
int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
int numbytes;
struct sockaddr_storage their_addr;
char buf[MAXBUFLEN];
socklen_t addr_len;
char s[INET6_ADDRSTRLEN];
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // set to AF_INET to force IPv4
hints.ai_socktype = SOCK_DGRAM;
hints.ai_flags = AI_PASSIVE; // use my IP
if ((rv = getaddrinfo(NULL, MYPORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1)
perror("listener: socket");
continue;
}
if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("listener: bind");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "listener: failed to bind socket\n");
return 2;
}
freeaddrinfo(servinfo);
while(1){
addr_len = sizeof their_addr;
if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0,
(struct sockaddr *)&their_addr, &addr_len)) == -1) {
perror("recvfrom");
exit(1);
}
buf[numbytes] = '\0';
string toRespond = theMove(buf, AG);
char * sendBack = new char[toRespond.size() + 1];
std::copy(toRespond.begin(), toRespond.end(), sendBack);
sendBack[toRespond.size()] = '\0';
sendto(sockfd, testing, strlen(testing), 0, (struct sockaddr *)&their_addr, addr_len);
}
Client:
int sockfd;
struct addrinfo hints, *servinfo, *p;
struct sockaddr_storage src_addr;
socklen_t src_addr_len = sizeof(src_addr);
int rv;
int numbytes;
if (argc != 3) {
fprintf(stderr,"usage: talker hostname message\n");
exit(1);
}
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_DGRAM;
if ((rv = getaddrinfo(argv[1], SERVERPORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}
// loop through all the results and make a socket
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("talker: socket");
continue;
}
break;
}
if (p == NULL) {
fprintf(stderr, "talker: failed to bind socket\n");
return 2;
}
char * chatBuff = (char*)malloc(sizeof(char)*512);
while(1){
scanf("%s", chatBuff);
if ((numbytes = sendto(sockfd, chatBuff, strlen(chatBuff), 0,
p->ai_addr, p->ai_addrlen)) == -1) {
perror("talker: sendto");
exit(1);
}
memset(chatBuff, '\0', sizeof(chatBuff));
if (recvfrom(sockfd, chatBuff, strlen(chatBuff), 0, (struct sockaddr*)&src_addr, &src_addr_len) == -1)
{
puts("throw computer out the stacks");
}
puts(chatBuff);
freeaddrinfo(servinfo);
printf("talker: sent %d bytes to %s\n", numbytes, argv[1]);
memset(chatBuff, '\0', sizeof(chatBuff));
}
memset(chatBuff, '\0', sizeof(chatBuff));
While not actually incorrect, this initializing of the entire buffer is cargo-cult nonsense when you intend to load it in the next line with a call that retuns the number of bytes loaded - that return would allow you to ensure a null-terminated string by setting one byte only. The only thing you must remember is that you must leave enough space for the null, either by oversizing the buffer or reducing the read length requested.
if (recvfrom(sockfd, chatBuff, strlen(chatBuff), 0, (struct sockaddr*)&src_addr, &src_addr_len) == -1)
In the (unnecessary and wasteful) line above, you use 'sizeof(chatBuff)' as the buffer size but then here, inexplicably, you shove in 'strlen(chatBuff)' - a RUNTIME CALL that returns the size of a null-terminated char array. Since you just set that array to all null, it returns zero, so your recvfrom() will always return with a 'buffer too small' error unless you receive an empty datagram.
So:
int bytesRec=recvfrom(sockfd, chatBuff, sizeof(chatBuff)-1, 0, (struct sockaddr*)&src_addr, &src_addr_len);
if(bytesRec<1) puts("throw computer out the stacks")
else chatBuff[bytesRec]=0;
In your server code, you are passing some unknown buffer named testing as the buffer to send, but you should be passing the sendBack buffer instead:
sendto(sockfd, sendBack, strlen(sendBack), 0, (struct sockaddr *)&their_addr, addr_len);
For that matter, you can eliminate sendBack and send the data from toRespond directly instead:
sendto(sockfd, toRespond.c_str(), toResponse.size(), 0, (struct sockaddr *)&their_addr, addr_len);
In both your server and client code, you are using AF_UNSPEC when calling getaddrinfo(). That is OK in a server, but generally not OK in a client. Imagine what happens if the server binds to an IPv6 address, but the client creates an IPv4 socket, or vice versa. Obvious mismatch, communication will not be possible (unless the server creates a dual-stack IPv6 socket that can accept both IPv4 and IPv6 packets). So in your client code, you should not use AF_UNSPEC. Use either AF_INET or AF_INET6, depending on what the server is actually bound to. If you must use AF_UNSPEC on the client side, then you need to call sendto() and recvfrom() for every possible server IP address until you receive a response from one of them.
Lastly, in your client code, your call to recvfrom() is assuming the response data will be no more than the same size as the data sent with sendto(). Is that actually the case? You did not show what theMove() does to the data the server receives, or how it generates a response. At the very least, you should replace strlen() with 512 when calling recvfrom(). Your client code is also assuming that the server's response will be null-terminated, but the server is not sending a null terminator in the data it echoes. So you need to terminate the buffer that you are passing to puts().
I am doing a toy server-client project(on linux) where multiple clients connect to server and do remote execution on server. What I have is a select() call which is supposed to tell me when a socket is readable. This is for both listen and accept new connection. Below I am posting a snippet.
int main() {
int sockfd;
fd_set readfds;
struct sockaddr_in serv_addr,cli_addr;
struct timeval tv;
socklen_t clilen = sizeof(cli_addr);
sockfd=socket(AF_INET, SOCK_STREAM, 0);
//setsockopt(sockid,IPPROTO_IPV6,IPV6_V6ONLY,(char *)&yes,sizeof(yes));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr =inet_addr("127.0.0.1");// INADDR_ANY;
serv_addr.sin_port = htons(40000);
if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
{
perror("bind");
}
while(1)
{
FD_ZERO(&readfds);
FD_SET(sockfd,&readfds);
tv.tv_sec=2;
tv.tv_usec=500000;
int result =select(sockfd+1,&readfds,NULL,NULL,&tv);
if(result<0) {
exit(-1);
}
else if(result>0) {
if(FD_ISSET(sockfd,&readfds)) {
//int newsockfd =accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
int newsockfd =accept(sockfd,NULL,NULL);
if(newsockfd<0) {
perror("accept");
}
}
}
}
return 0;
}
But the select in the above code is always succeeding irrespective of the presence of any client and the accept is throwing error:
"accept: Invalid argument" and keep on looping, select is not even waiting for the timeout. Can someone please explain what is problem with my code. Am I not using select the right way it is supposed to be used(I am using it for the first time)?
You forgot to call listen after bind.
Actually, I want to create an application in C such that 2 people can chat with each other. Let us assume they know their IP (Actually, I think I am making the mistake here. I get my IPs from www.whatismyip.com).
void recv_data(char *from, unsigned short int Port, char *data, int data_length)
{
WSADATA wsaData;
SOCKET RecvSocket;
sockaddr_in RecvAddr;
char RecvBuf[data_length];
sockaddr_in SenderAddr;
int SenderAddrSize = sizeof (SenderAddr);
WSAStartup(MAKEWORD(2, 2), &wsaData);
RecvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
RecvAddr.sin_family = AF_INET;
RecvAddr.sin_port = htons(Port);
RecvAddr.sin_addr.s_addr = inet_addr(from);
bind(RecvSocket, (SOCKADDR *) & RecvAddr, sizeof (RecvAddr));
recvfrom(RecvSocket, RecvBuf, data_length, 0, (SOCKADDR *) & SenderAddr, &SenderAddrSize);
int i;
for(i=0;i<=data_length-1;i++)
*(data+i)=RecvBuf[i];
WSACleanup();
}
The above is a function to receive what the other person is sending. It works great when "127.0.0.1" is the value of from but when my ip (117.193.52.176) is used, something else appears. Could anyone tell me where I am wrong ?
The address you passing to "bind" is likely wrong. Just use the IP of INADDR_ANY (0) for the call to bind. I suspect 117.193.52.176 is likely your external IP address outside of your home NAT. Your PC's real IP address is 192.168.1.2 or something like that. Type "ipconfig /all" from the command line. In any case, just bind to INADDR_ANY so you don't have to know your real IP address.
Other issues with this code:
Not checking return values from socket APIs
Don't call WSAStartup and WSACleanup for every recvfrom call. Just call WSAStartup once in your app, and don't worry about calling WSACleanup.
I'm not entirely sure if the line "char RecvBuf[data_length];" will compile. (Dynamically length static buffer on the stack? Maybe it's a new compiler feature).
Don't create a new socket for every recvfrom call. Create it once and bind to it, then use it for all subsequent send/recv calls.
5.. A more fundamnetal design problem. Unless both you and person you are communicating with are directly connected to the Internet (not NAT and no firewall), sending and receiving UDP packets will be difficult. Read the article on hole-punching here.
In any case, here's a cleaner version of your code:
int g_fWinsockInit = 0;
void initWinsock()
{
WSADATA wsaData = {};
if(!g_fWinsockInit)
{
WSAStartup(MAKEWORD(2,2), &wsaData);
g_fWinsockInit = 1;
}
}
void recv_data(char *from, unsigned short int Port, char *data, int data_length)
{
SOCKET RecvSocket;
sockaddr_in RecvAddr = {}; // zero-init, this will implicitly set s_addr to INADDR_ANY (0)
sockaddr_in SenderAddr = {}; // zero-init
int SenderAddrSize = sizeof(SendAddr);
int ret;
initWinsock();
RecvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (RecvSocket == INVALID_SOCK)
{
printf("Error - socket failed (err = %x)\n", WSAGetLastError());
return;
}
RecvAddr.sin_family = AF_INET;
RecvAddr.sin_port = htons(Port);
ret = bind(RecvSocket, (SOCKADDR *) & RecvAddr, sizeof (RecvAddr));
if (ret < 0)
{
printf("bind failed (error = %x)\n", WSAGetLastError());
return;
}
ret = recvfrom(RecvSocket, data, data_length, 0, (SOCKADDR *) &SenderAddr, &SenderAddrSize);
if (ret < 0)
{
printf("recvfrom failed (error = %x)\n", WSAGetLastError());
}
else
{
printf("received %d bytes\n");
}
}
I am writing some simple client/server code using UDP. The program works fine, but if I only start the client, the recvfrom method does not block. However, when I remove the sendto method, recvfrom starts to block. Any idea of what is going on?
Here is the client side code:
int server_length; /* Length of server struct */
char send_buffer[256] = "hi"; /* Data to send */
time_t current_time; /* Time received */
while(true)
{
/* Tranmsit data to get time */
server_length = sizeof(struct sockaddr_in);
if (sendto(m_oSocket, send_buffer, (int)strlen(send_buffer) + 1, 0, (struct sockaddr *)&m_oServer, server_length) == -1)
{
fprintf(stderr, "Error transmitting data.\n");
continue;
}
/* Receive time */
if (recvfrom(m_oSocket, (char *)¤t_time, (int)sizeof(current_time), 0, (struct sockaddr *)&m_oServer, &server_length) < 0)
{
fprintf(stderr, "Error receiving data.\n");
continue;
}
/* Display time */
printf("Current time: %s\n", ctime(¤t_time));
Sleep(1000);
}
And here is the initialization:
unsigned short m_iPortnumber;
struct sockaddr_in m_oServer;
struct sockaddr_in m_oClient;
SOCKET m_oSocket;
WSADATA w; /* Used to open Windows connection */
int a1, a2, a3, a4; /* Server address components in xxx.xxx.xxx.xxx form */
a1 = 192;
a2 = 168;
a3 = 2;
a4 = 14;
m_iPortnumber = 52685;
/* Open windows connection */
if (WSAStartup(0x0101, &w) != 0)
{
fprintf(stderr, "Could not open Windows connection.\n");
exit(0);
}
/* Open a datagram socket */
m_oSocket = socket(AF_INET, SOCK_DGRAM, 0);
if (m_oSocket == INVALID_SOCKET)
{
fprintf(stderr, "Could not create socket.\n");
WSACleanup();
exit(0);
}
/* Clear out server struct */
memset((void *)&m_oServer, '\0', sizeof(struct sockaddr_in));
/* Set family and port */
m_oServer.sin_family = AF_INET;
m_oServer.sin_port = htons(m_iPortnumber);
/* Set server address */
m_oServer.sin_addr.S_un.S_un_b.s_b1 = (unsigned char)a1;
m_oServer.sin_addr.S_un.S_un_b.s_b2 = (unsigned char)a2;
m_oServer.sin_addr.S_un.S_un_b.s_b3 = (unsigned char)a3;
m_oServer.sin_addr.S_un.S_un_b.s_b4 = (unsigned char)a4;
/* Clear out client struct */
memset((void *)&m_oClient, '\0', sizeof(struct sockaddr_in));
/* Set family and port */
m_oClient.sin_family = AF_INET;
m_oClient.sin_addr.s_addr=INADDR_ANY;
m_oClient.sin_port = htons(0);
/* Bind local address to socket */
if (bind(m_oSocket, (struct sockaddr *)&m_oClient, sizeof(struct sockaddr_in)) == -1)
{
fprintf(stderr, "Cannot bind address to socket.\n");
closesocket(m_oSocket);
WSACleanup();
exit(0);
}
There are a variety of ways that sendto can fail. Some, such as arp failure, will cause an error during sendto. Other, such as ICMP port unreachable, may be reported when you next use the socket.
Your recvfrom call could actually be fetching the ICMP packet sent in response to your outgoing packet.
Does a second recvfrom block as expected?
Socket required to be set BLOCKING/NON-BLOCKING.
Set BLOCKING
int nMode = 0; // 0: BLOCKING
if (ioctlsocket (objSocket, FIONBIO, &nMode) == SOCKET_ERROR)
{
closesocket(SendingSocket);
WSACleanup();
return iRet;
}
Set NON-BLOCKING
int nMode = 1; // 1: NON-BLOCKING
if (ioctlsocket (objSocket, FIONBIO, &nMode) == SOCKET_ERROR)
{
closesocket(SendingSocket);
WSACleanup();
return iRet;
}
It looks like you're setting up the server socket and the client socket the same way. The initialization looks good for a server, but for the client, you'll want to bind to port 0.
In fact, for both of them you can do INADDR_ANY (IP 0.0.0.0), which doesn't bind to a specific interface, but instead allows any connection on the correct port.