简体   繁体   中英

Socket C++ program successfully compiled crashes at runtime

I've been struggling with this for hours, but I couldn't manage to find out what am I doing wrong. This is a very simple program that SHOULD send out a simple UDP packet to a given IP on a given port. g++ compiles this program without any error or warning, but when I run it...! It just dies. On stdout it prints: 0 (this should mean binding worked correctly) and "TRYING TO SEND". And then nothing. It simply doesn't print "HERE I AM". No errors, no messages, nothing. Does anybody have any hint? Here is the code:

#include <iostream>
#include <string.h>
#include <time.h>
#include <stdio.h>

#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <errno.h>
#include <unistd.h>
#include <netdb.h>
#include <ifaddrs.h>

using namespace std;

int main()
{
    struct sockaddr_in local_addr;
    local_addr.sin_family=AF_INET;
    local_addr.sin_port=0;
    local_addr.sin_addr.s_addr=htonl(INADDR_ANY);
    memset(local_addr.sin_zero, '\0', sizeof(local_addr.sin_zero));

    int local_socket;
    local_socket = socket(PF_INET, SOCK_STREAM, 0);
    cout<<bind(local_socket, (struct sockaddr *)&local_addr, sizeof(sockaddr_in))        <<endl;;


    char remote_addr[]="95.110.232.188";

    struct sockaddr_in remote_sockaddr;
    remote_sockaddr.sin_family=AF_INET;
    remote_sockaddr.sin_port=1180;
    remote_sockaddr.sin_addr.s_addr=inet_addr(remote_addr);
    memset(remote_sockaddr.sin_zero, '\0', sizeof(remote_sockaddr.sin_zero));
    cout<<"TRYING TO SEND.."<<endl;
    cout<<sendto(local_socket, "PTDMW", 5, 0, (struct sockaddr *) & remote_sockaddr, sizeof(sockaddr_in))<<endl;
    cout<<"HERE I AM!!"<<endl;  

}

SOCK_STREAM is for TCP, not UDP. Use SOCK_DGRAM . And don't forget to change to network byte order on the port number and other host specific values. Other than that your program runs fine and doesn't crash (if you change the socket to the right type).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM