Source_Of_it_all
Source_Of_it_all

Reputation: 3

C++ bind UDP Socket Address Family not suppoerted

Running a Linux system on a PowerPC Architecture which is connected via Ethernet to another Device obtaining a UDP connection (Package Based), I try to setup a socket and bind it to my Port 8813. But whenever I enter a Port different from 0, Binding fails.

Here is the code:

int connector::initUDPSocket(){
    struct hostent *server;
    //Construct Socket
    struct sockaddr_in {
        __uint8_t sin_len;
        sa_family_t sin_family;
        in_port_t sin_port;
        struct in_addr sin_addr;
        char sin_zero[8];
    }
    ;
    sockaddr_in socketaddress;
    socklen_t addrlen = sizeof(struct sockaddr_in); /* length of addresses */


    udpsocket=socket(AF_INET,SOCK_DGRAM ,0);

    if(udpsocket<=0)
    {
        printf("No Socket opened!");
        return 1;
    }
    else
    {
        printf("ONE Socket opened!");

        memset((char *) &socketaddress,0, sizeof(socketaddress));


        socketaddress.sin_family = AF_INET;
        socketaddress.sin_addr.s_addr=htonl(inet_addr("192.168.0.10"));//<=That's the external devices address;// htonl(inet_addr("192.168.0.1"));//<=That's my devices address;//htonl(INADDR_ANY);//INADDR_ANY;//
        socketaddress.sin_port = htons(8813);//8813;//htonl(8813);//htons(0); //<=Only the last one works


        int bind_result=bind(udpsocket,(struct sockaddr *)&socketaddress,sizeof(socketaddress));
        if( bind_result == SOCKET_ERROR)
        {

            printf(LFL_CRI,"BIND failed! Error: %s",strerror(errno)); //Returns "BIND failed! Error: Address family not supported by protocol"
        }
        else
        {
            printf(LFL_CRI,"BIND worked!");
                //Nun den Listener für den DatenStream aufsetzen.
                char      SockAddrBuffer[sizeof(struct sockaddr_storage)];
                socklen_t SockAddrBufferSize = sizeof(SockAddrBuffer);
                int numofbytes=recvfrom(udpsocket, udp_buffer, UDP_BUFFERSIZE, 0, (struct sockaddr *)SockAddrBuffer, &SockAddrBufferSize);
                if (numofbytes >0)
                {
                    printf("%i bytes received",numofbytes);
                }
            }

        }
        return 0;
    }
}

What I found out so far:

So, 2 questions are open here:

  1. What am I doing wrong?

  2. What am I understanding wrong about "bind". What sense does it make to listen to "some random port assigned to my program by the system"? I mean, if I setup an http-Server, I want to listen to Port 80 and not to port "RANDOM". What is this good for?

Upvotes: 0

Views: 1107

Answers (1)

dbush
dbush

Reputation: 223689

You've redefined struct sockaddr_in in your code. If is in any way different from how the system defines it, any code that attempts to use this struct will not work properly.

You need to #include <netinet/in.h> to get the proper definition of this struct.

Upvotes: 1

Related Questions