BSD Socket~UDP~Code examples

C 代码,可以用于OSX运行

/*
Client-server example using UDP[edit]
The User Datagram Protocol (UDP) is a connectionless protocol with no guarantee of delivery. UDP packets may arrive out of order, multiple times, or not at all. Because of this minimal design, UDP has considerably less overhead than TCP. Being connectionless means that there is no concept of a stream or permanent connection between two hosts. Such data are referred to as datagrams (Datagram Sockets).

UDP address space, the space of UDP port numbers (in ISO terminology, the TSAPs), is completely disjoint from that of TCP ports.

Code may set up a UDP server on port 7654 as follows:

*/

#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h> /* for close() for socket */
#include <stdlib.h>

int main(void)
{
  int sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
  struct sockaddr_in sa;
  char buffer[1024];
  ssize_t recsize;
  socklen_t fromlen;

  memset(&sa, 0, sizeof sa);
  sa.sin_family = AF_INET;
  sa.sin_addr.s_addr = htonl(INADDR_ANY);
  sa.sin_port = htons(7654);
  fromlen = sizeof(sa);

  if (-1 == bind(sock,(struct sockaddr *)&sa, sizeof(sa)))
  {
    perror("error bind failed");
    close(sock);
    exit(EXIT_FAILURE);
  }

  for (;;)
  {
    printf ("recv test....\n");
    recsize = recvfrom(sock, (void *)buffer, sizeof(buffer), 0, (struct sockaddr *)&sa, &fromlen);
    if (recsize < 0) {
      fprintf(stderr, "%s\n", strerror(errno));
      exit(EXIT_FAILURE);
    }
    printf("recsize: %d\n ", recsize);
    sleep(1);
    printf("datagram: %.*s\n", (int)recsize, buffer);
  }
}

/*
This infinite loop receives any UDP datagrams to port 7654 using recvfrom(). It uses the parameters:

socket
pointer to buffer for data
size of buffer
flags (same as in recv or other receive socket function)
address struct of sending peer
length of address struct of sending peer.
*/

Client

/*
A simple demonstration of sending a UDP packet containing the string "Hello World!" to address 127.0.0.1 and port 7654 might look like this:

*/

#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>

int main(int argc, char *argv[])
{
  int sock;
  struct sockaddr_in sa;
  int bytes_sent;
  char buffer[200];

  strcpy(buffer, "hello world!");

  //create an internet, datagram, socket using UDP
  sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
  if (-1 == sock) /* if socket failed to initialize, exit */
    {
      printf("Error Creating Socket");
      exit(EXIT_FAILURE);
    }

  //Zero out socket address
  memset(&sa, 0, sizeof sa);

  //The address is ipv4
  sa.sin_family = AF_INET;

   //ip_v4 adresses is a uint32_t, convert a string representation of the octets to the appropriate value
  sa.sin_addr.s_addr = inet_addr("127.0.0.1");

  //sockets are unsigned shorts, htons(x) ensures x is in network byte order, set the port to 7654
  sa.sin_port = htons(7654);

  //sendto(int socket, char data, int dataLength, flags, destinationAddress, int destinationStructureLength)
  bytes_sent = sendto(sock, buffer, strlen(buffer), 0,(struct sockaddr*)&sa, sizeof sa);
  if (bytes_sent < 0) {
    printf("Error sending packet: %s\n", strerror(errno));
    exit(EXIT_FAILURE);
  }

  close(sock); /* close the socket */
  return 0;
}

/*
In this code, buffer is a pointer to the data to be sent, and buffer_length specifies the size of the data.
*/

Link:BSD Socket Wiki 一下

BSD Socket~UDP~Code examples

时间: 2024-11-02 18:40:10

BSD Socket~UDP~Code examples的相关文章

BSD Socket~TCP~Example Code

TCP 协议实现 C版本,可用于Mac OS X机器上运行 Server: /* Setting up a simple TCP server involves the following steps: Creating a TCP socket, with a call to socket(). Binding the socket to the listen port, with a call to bind(). Before calling bind(), a programmer mu

BSD socket API

伯克利套接字(Berkeley sockets),也称为BSD Socket.伯克利套接字的应用编程接口(API)是采用C语言的进程间通信的库,经常用在计算机网络间的通信. BSD Socket的应用编程接口已经是网络套接字的抽象标准.大多数其他程序语言使用一种相似的编程接口.它最初是由加州伯克利大学为Unix系统开发出来的.所有现代的操作系统都实现了伯克利套接字接口,因为它已经是连接互联网的标准接口了. API函数 这些是伯克利套接字提供的库函数. socket() 创造某种类型的套接字,分配

socket error code

Error Codes The ERRNO values below are set when API calls fail. Use xn_getlasterror to retrieve the error code after an API call fails. Functionxn_geterror_string) can be used to retrieve the string name of a particular error code. All errno values a

AWS s3 python sdk code examples

Yet another easy-to-understand, easy-to-use aws s3 python sdk code examples. github地址:https://github.com/garyelephant/aws-s3-python-sdk-examples. """ Yet another s3 python sdk example. based on boto 2.27.0 """ import time imp

Java vs. Python (1): Simple Code Examples

Some developers have claimed that Python is more productive than Java. It is dangerous to make such a claim, because it may take several days to prove that thoroughly. From a high level view, Java is statically typed, which means all variable names h

【windows socket+UDP服务器客户端】

Windows Socket+UDP服务器客户端 Winsock是 Windows下套接字标准.                    1.UDP socket编程:          UDP(用户数据报协议)是一个无连接,不可靠的数据传输,其特点是简单,快捷.相比与TCP,UDP不需要建立连接(不需connect.accept函数),数据发送接收之后,不需要终止连接.基于UDP的程序,避免了TCP运行的开销,在效率与速度上具有更好的表现.          UDP是无连接的,可能会有数据的丢失

[转]Java Code Examples for android.util.JsonReader

[转]Java Code Examples for android.util.JsonReader The following are top voted examples for showing how to use android.util.JsonReader. These examples are extracted from open source projects. You can vote up the examples you like and your votes will b

bsd socket 简单封装。支持android、ios、mac osx

cocos2d-x官方没有封装原生socket,只提供了websocket,如果我们需要socket,不同团队有不同的造轮子的方案,其中使用Asio库的比较多,但是Asio库太过于庞大,我不太想用.其实只需要简单封装一下bsd socket就好了,几十行代码而已. 注意如果在android中测试,需要添加网络访问权限,而且不能在主线程中使用. 贴一发代码,只是简单测试了下,如果有问题再慢慢完善. 1 #ifndef __cpp_test__Socket__ 2 #define __cpp_tes

Java Code Examples for javax.servlet.http.Part

http://www.programcreek.com/java-api-examples/index.php?api=javax.servlet.http.Part The following are 20 Jave code examples that show how to use the javax.servlet.http.Part class. These examples are extracted from open source projects. You can click