Linux+udp+server+client

Source: Internet
Author: User
Tags socket error htons

First, the client

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <unistd.h>

#include <stdio.h>

#include <errno.h>

#include <time.h>

#include <string.h>

void Main ()

{

char send_data[20]= "IM sender data";

int FD;

struct sockaddr_in local_addr,to_addr;

fd=Socket(af_inet,scok_dgram,0);

if (fd<0)

{

printf ("Create socket Error");

Return

}

Local_addr.sin_family=af_inet;

Local_addr.sin_port=htons (7777);

Local_addr.sin_addr.s_addr=inaddr_any;

To_addr.sin_family=af_inet;

To_addr.sin_port=htons (8888);

To_addr.sin_addr.s_addr=inaddr_any;

if ( -1 = = bind(fd, (struct sockaddr*) &local_addr,sizeof (LOCAL_ADDR)))

{

printf ("Bind error\n);

Close (FD);

Return

}

printf ("bind success");

while (1)

{

Sleep (1);

if ( -1! = sendto(fd,send_data,sizeof (Send_data), 0, (struct sockaddr*) &to_addr,sizeof (TO_ADDR)))

printf ("Send success\n");

Else

printf ("Send error\n");

}

}

Second, the server

#include <sys/types.h>

#include <sys/socket.h>

#include <netinet/in.h>

#include <arpa/inet.h>

#include <unistd.h>

#include <stdio.h>

#include <errno.h>

#include <time.h>

#include <string.h>

void Main ()

{

int FD;

int n;

Char rcv_buf[256];

Socklen_t Servlen;

struct sockaddr_in from_addr,temp_addr;

fd=Socket(as_inet,sock_dgram,0);

if (fd<0)

{

printf ("Create socket Error");

Return

}

From_addr.sin_family=af_inet;

From_addr.sin_port=htons (8888);

From_addr.sin_addr.s_addr=inaddr_any;

Servlen=sizeof (TEM_ADDR);

if ( -1 = = bind(FD, (struck sockaddr*) &from_addr,sizeof (struck sockaddr_in)))

{

printf ("Bind error");

Return

}

while (1)

{

Bzero (rcv_buf,256);

n=rcvfrom(fd,rcv_buf,256,0, (struct sockaddr*) &temp_addr,&servlen);

rcv_buf[n]=0;

printf ("rcvdata:%s\n", rcv_buf);

}

}

Linux+udp+server+client

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.