sp_sendmsg <ip_address>, <port_number>, <message>
<ip_address>
是运行着 UDP 应用程序的计算机的 IP 地址。
<port_number>
是 UDP 端口的端口号。
<message>
是要发送的消息,长度不超过 4096 个字符。
sp_sendmsg "120.10.20.5", 3456, "Hello World"
这个示例 C 程序监听指定的端口,并输出它接收到的消息。例如,若要接收此示例中调用 sp_sendmsg 发送的消息,请使用:
updmon 3456
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <fcntl.h>
main(argc, argv)
int argc; char *argv[];
{
struct sockaddr_in sadr;
int portnum,sck,dummy,msglen;
char msg[256];
if (argc < 2) {
printf(“Usage: udpmon <udp portnum>\n”);
exit(1);
}
if ((portnum=atoi(argv[1])) < 1) {
printf("Invalid udp portnum\n");
exit(1);
}
if ((sck=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP)) < 0) {
printf("Couldn't create socket\n");
exit(1);
}
sadr.sin_family = AF_INET;
sadr.sin_addr.s_addr = inet_addr("0.0.0.0");Sends the message "Hello World" to IP address 120.10.20.5 using port
3456:
if (bind(sck,&sadr,sizeof(sadr)) < 0) {
printf("Couldn't bind requested udp port\n");
exit(1);
}
for (;;)
{
if((msglen=recvfrom(sck,msg,sizeof(msg),0,NULL,&dummy)) < 0)
printf("Couldn't recvfrom() from udp port\n");
printf("%.*s\n", msglen, msg);
}
}
使用 sp_sendmsg 时,还存在一些其它注意事项: