USR-TCP232-302 User Manual
h.usriot.com
Jinan USR IOT Technology Limited
49 / 53
27.
memset((void *)&clientaddr, 0, sizeof(clientaddr));
28.
hostaddr.sin_family = AF_INET;
29.
hostaddr.sin_port = htons(LISTEN_PORT);
30.
hostaddr.sin_addr.s_addr = htonl(INADDR_ANY);
31.
listen_sock = socket(AF_INET, SOCK_STREAM, 0);
32.
if(listen_sock < 0)
33.
{
34.
syslog(LOG_ERR, "%s:%d, create socket failed", __FILE__, __LINE__);
35.
exit(1);
36.
}
37.
if(bind(listen_sock, (struct sockaddr *)&hostaddr, sizeof(hostaddr)) < 0)
38.
{
39.
syslog(LOG_ERR, "%s:%d, bind socket failed", __FILE__, __LINE__);
40.
exit(1);
41.
}
42.
if(listen(listen_sock, MAX_LISTEN_NUM) < 0)
43.
{
44.
syslog(LOG_ERR, "%s:%d, listen failed", __FILE__, __LINE__);
45.
exit(1);
46.
}
47.
while(1)
48.
{
49.
app_sock = accept(listen_sock, (struct sockaddr *)&clientaddr, &socklen);
50.
if(app_sock < 0)
51.
{
52.
syslog(LOG_ERR, "%s:%d, accept failed", __FILE__, __LINE__);
53.
exit(1);
54.
}
55.
sprintf(sendbuf, "welcome %s:%d here!/n", inet_ntoa(clientaddr.sin_addr.s_addr), clientaddr.sin_port);
56.
//send data
57.
sendlen = strlen(sendbuf) +1;
58.
retlen = 0;
59.
leftlen = sendlen;
60.
ptr = sendbuf;
61.
//while(leftlen)
62.
{
63.
retlen = send(app_sock, ptr, sendlen, 0);
64.
if(retlen < 0)
65.
{
66.
if(errno == EINTR)
67.
retlen = 0;
68.
else
69.
exit(1);
70.
}
71.
leftlen -= retlen;