0

I am working on socket programming(UDP sockets) in Windows-form application. I have called socket() on button click then I want send some bytes on other button click.Sendto() is returning 0 when I click the desired button but data is not received on the other end but when I call sendto() from a different thread within the same application it works fine.

Below is function to call socket():

int socket_create(String^* error,SOCKET *sock_fd,int port_number)
{
    sockaddr_in my_addr;
    *sock_fd = INVALID_SOCKET;

    // Create a SOCKET for the server to listen for client connections
    *sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (*sock_fd == INVALID_SOCKET)
    {
        this->richTextBox1->AppendText("Error at socket():"+     WSAGetLastError() + "\n");
        return -1;
    }
    else 
        this->richTextBox1->AppendText("Socket succesfully opened on port number: " + port_number + "\n");
    // The sockaddr_in structure specifies the address family,
    // IP address, and port for the socket that is being bound.
    my_addr.sin_family = AF_INET;
    my_addr.sin_addr.s_addr = inet_addr("192.168.1.2");
    my_addr.sin_port = htons(port_number);

    if (bind(*sock_fd, (SOCKADDR *) & my_addr, sizeof (my_addr)) == SOCKET_ERROR)
    {
        this->richTextBox1->AppendText("bind failed:" + WSAGetLastError()+ "\n");
        //freeaddrinfo(result);
        closesocket(*sock_fd);
        return -1;
    }
    else
        this->richTextBox1->AppendText("Bind succesful on port number:" + port_number + "\n");
    return 0;
}

Below is button code which calls socket_create() to open socket:

private: System::Void Connect_btn_Click(System::Object^  sender, System::EventArgs^  e) 
{
    int status = 0;
    String^ error;
    status = socket_create(&error, &s_8888,8888);   
}

socket descriptor s_8888 is defined globally.

Below is button code to call sendto():

private: System::Void test_btn_Click(System::Object^  sender, System::EventArgs^  e) 
{
    sockaddr_in their_addr;
    their_addr.sin_family = AF_INET;
    their_addr.sin_addr.s_addr = inet_addr(ip_address);
    their_addr.sin_port = htons(8888);
    int length = sizeof (their_addr);
    i=sendto(s_8888 , buf , sizeof(buf), 0, (SOCKADDR *) &their_addr, length);
    if(i== SOCKET_ERROR)
    {
        MessageBox::Show("" + WSAGetLastError());
    }
    richTextBox1->AppendText("" + i + "\n");
}

I am unable to understand why it is behaving like that and how to resolve it?

Saad Rafey
  • 531
  • 2
  • 6
  • 18
  • The most important code in any "it doesn't work" question is the error checking code. There isn't any in this one. You cannot find out why it doesn't work when you don't check. Use System::Net::UdpClient so any failures produce a good diagnosable exception. Use TCP to get a delivery guarantee. – Hans Passant May 16 '15 at 09:05
  • @HansPassant I have updated my question with error checking – Saad Rafey May 16 '15 at 09:16

0 Answers0