在我这里OK的!!!
代码如下
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVER_PORT_NUM 5000
STATUS TestA ( char * serverName /* name or IP address of server */ )
{
char myRequest[] = /* request to send to server */
"Request From Machine A!! Some Context Here )))))))))))))))))))))))))))))))))))))))) ";
struct sockaddr_in serverAddr; /* server's socket address */
int sockAddrSize; /* size of socket address structure */
int sFd; /* socket file descriptor */
/* create client's socket */
if ((sFd = socket (AF_INET, SOCK_DGRAM, 0)) == ERROR)
{
perror ("socket");
return (ERROR);
}
sockAddrSize = sizeof (struct sockaddr_in);
bzero ((char *) &serverAddr, sockAddrSize);
serverAddr.sin_len = (u_char) sockAddrSize;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons (SERVER_PORT_NUM);
if (((serverAddr.sin_addr.s_addr = inet_addr (serverName)) == ERROR) &&
((serverAddr.sin_addr.s_addr = hostGetByName (serverName)) == ERROR))
{
perror ("unknown server name");
close (sFd);
return (ERROR);
}
FOREVER
{
while(OK!=ping(serverName,5,0))
taskDelay(sysClkRateGet()<<2);
printf("Ping OK ,run Socket!\n");
while (sendto (sFd, (caddr_t) &myRequest, sizeof (myRequest), 0,
(struct sockaddr *) &serverAddr, sockAddrSize) != ERROR) ;
perror ("sendto");
taskDelay(sysClkRateGet()<<2);
}
close (sFd);
return OK;
}
STATUS TestB ( )
{
struct sockaddr_in serverAddr; /* server's socket address */
struct sockaddr_in clientAddr; /* client's socket address */
char clientRequest[1024]; /* request/Message from client */
int sockAddrSize; /* size of socket address structure */
int sFd; /* socket file descriptor */
/* set up the local address */
sockAddrSize = sizeof (struct sockaddr_in);
bzero ((char *) &serverAddr, sockAddrSize);
serverAddr.sin_len = (u_char) sockAddrSize;
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons (SERVER_PORT_NUM);
serverAddr.sin_addr.s_addr = htonl (INADDR_ANY);
/* create a UDP-based socket */
if ((sFd = socket (AF_INET, SOCK_DGRAM, 0)) == ERROR)
{
perror ("socket");
return (ERROR);
}
/* bind socket to local address */
if (bind (sFd, (struct sockaddr *) &serverAddr, sockAddrSize) == ERROR)
{
perror ("bind");
close (sFd);
return (ERROR);
}
/* read data from a socket and satisfy requests */
FOREVER
{
if (recvfrom (sFd, (char *) &clientRequest, sizeof (clientRequest), 0,
(struct sockaddr *) &clientAddr, &sockAddrSize) == ERROR)
{
perror ("recvfrom");
}
else printf(".");
}
close (sFd);
return OK;
}
机器甲运行
TestA ("192.168.31.2");
机器乙运行
TestB();
谁在先都试过,没问题,甲在先,会慢一些,因为arp有发送间隔的,比ping的调用要少很多。
注意确保两台target有不同的IP地址和物理地址(Mac地址).
不知道楼主的问题出在那里,希望楼主能临时找个Hup,拉几根网线过去,Hub可以放在远一些方便的地方。