Related functions: Send, Sendmsg, recv, recvfrom, socket
Header files: #include <sys/types.h> #include <sys/socket.h>
Define functions: int sendto (int s, const void * msg, int len, unsigned int flags, const struct SOCKADDR * to, int tolen);
Function Description: SendTo () is used to pass data from the specified socket to the other host. The parameter s is a socket that has been wired, and if the UDP protocol is used, it does not need to be connected. Parameter msg points to the data content to be connected, the parameter flags general set 0, detailed description please refer to send (). The parameter to is used to specify the network address to be transmitted, and the structure sockaddr refer to bind (). The parameter tolen is the result length of sockaddr.
Return value: Success returns the number of characters actually delivered, failure returns 1, and the reason for the error is stored in errno.
Error code:
1, EBADF parameter s illegal socket processing code.
2. The Efault parameter has a pointer to the memory space that cannot be accessed.
3. Wnotsock Canshu S is a file description word, non-socket.
4, Eintr was interrupted by the signal.
5, Eagain This action will cause the process to block, but the soket of the parameter S for the missed lesson block.
6, ENOBUFS system buffer memory is insufficient.
7, EINVAL passed to the system call parameter is not correct.
Example
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet.in.h>
#include <arpa.inet.h>
#define PORT 2345/* Used by Port */
Main ()
{
int SOCKFD, Len;
struct sockaddr_in addr;
Char buffer[256];
Creating sockets
if (SOCKFD = socket (af_inet, SOCK_DGRAM, 0)) < 0)
{
Perror ("socket");
Exit (1);
}
Fill in the SOCKADDR_IN structure
Bzero (&addr, sizeof (addr));
addr.sin_family = af_inet;
Addr.sin_port = htons (port);
ADDR.SIN_ADDR = Hton1 (Inaddr_any);
if (Bind (SOCKFD, &addr, sizeof (addr)) < 0)
{
Perror ("Connect");
Exit (1);
}
while (1)
{
Bezro (buffer, sizeof (buffer));
Len = recvfrom (socket, buffer, sizeof (buffer), 0, &addr &addr_len);
Displays the network address of the client side
printf ("Receive from%s\n", Inet_ntoa (ADDR.SIN_ADDR));
Return a string to client side
SendTo (sockfd, buffer, len, 0, &addr, Addr_len);
}
}
C Language SendTo () function: transmit data via socket