UDP socket code

Source: Internet
Author: User
Tags htons

Server (acceptor) Program:

1. Create a socket)

2. Bind the socket to a local address and port (BIND)

3. Data to be received (recvfrom)

4. Disable socket.

Client (sender) Program

1. Create a socket)

2. Send data (sendto) to the server)

3. Close the socket.

Server code:

# Include <winsock2.h>

# Include <stdio. h>

Void main ()

{

Word wversionrequested;

Wsadata;

Int err;

Wversionrequested = makeword (1, 1 );

Err = wsastartup (wversionrequested, & wsadata );

If (Err! = 0)

{

Reutrn;

}

If (lobyte (wsadata. wversion )! = 1 | hibyte (wsadata. wversion )! = 1)

{

Wsacleanup ();

Return;

}

Socket socksrv = socket (af_inet, sock_dgram, 0 );

Sockaddr_in addrsrv;

Addrsrv. sin_addr.s_un.s_addr = htonl (inaddr_any );

Addrsrv. sin_family = af_inet;

Addrsrv. sin_port = htons (6000 );

BIND (socksrv, (sockaddr *) & addrsrv, sizeof (sockaddr ));

Sockaddr_in addrclient;

Int Len = sizeof (sockaddr );

Char recvbuf [100];

Recvfrom (socksrv, recvbuf, 100,0, (sockaddr *) & addrclient, & Len );

Printf ("% s/n", recvbuf );

Cloasesocket (socksrv );

Wsacleanup ();

}

Client Lu code:

# Include (winsock2.h>

# Include <stdio. h>

Void main ()

{

Word wversionrequested;

Wsadata;

Int err;

Wversionrequested = makeword (1, 1 );

Err = wsastartup (wversionrequested, & wsadata );

If (Err! = 0)

{

Return;

}

If (lobyte (wsadata. wversion )! = 1 | hibyte (wsadata. wversion )! = 1)

{

Wsacleanup ();

Return;

}

Socket sockclient = socket (af_inet, sock_dgram <0 );

Sockaddr_in addrsrv;

Addrsrv. sin_addr.s_un.s_addr = inet_addr ("127.0.0.1 ");

Addrsrv. sin_family = af_inet;

Addrsrv. sin_port = htons (6000 );

Sendto (sockclient, "hello", strlen ("hello") + 1,0, (sockaddr *) & addrsrv, sizeof (sockaddr )):

Closesocket (sockclient );

Wsacleanup ();

}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.