Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* fpont 12/99 */
- /* pont.net */
- /* udpServer.c */
- #include <sys/types.h>
- #include <sys/socket.h>
- #include <netinet/in.h>
- #include <netdb.h>
- #include <stdio.h> //printf
- #include <stdlib.h>
- #include <arpa/inet.h>
- #include <linux/if_packet.h>
- #include <string.h> //strncpy
- #include <sys/ioctl.h>
- #include <sys/socket.h>
- #include <net/if.h> //ifreq
- #include <unistd.h> //close
- #include <netinet/ether.h>
- #include <sys/time.h> //gettimeofday
- #include <pthread.h>
- #include <string.h>
- #include <arpa/inet.h>
- #include <netinet/in.h>
- #include <sys/ioctl.h>
- #include <linux/if_packet.h>
- #include <time.h>
- #include <math.h>
- //#include <stdlib.h>
- //#include <sys/types.h>
- //#include <sys/socket.h>
- //#include <netinet/in.h>
- //#include <arpa/inet.h>
- //#include <netdb.h>
- //#include <stdio.h>
- //#include <unistd.h> /* close() */
- //#include <string.h> /* memset() */
- //#include <time.h>
- #define LOCAL_SERVER_PORT 1500
- #define MAX_MSG 100
- void printCurrentTime();
- int main(int argc, char *argv[]) {
- int sd, rc, n, cliLen;
- struct sockaddr_in cliAddr, servAddr;
- char msg[MAX_MSG];
- /* socket creation */
- sd=socket(AF_INET, SOCK_DGRAM, 0);
- if(sd<0) {
- printf("%s: cannot open socket \n",argv[0]);
- exit(1);
- }
- /* bind local server port */
- servAddr.sin_family = AF_INET;
- //servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
- servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
- servAddr.sin_port = htons(LOCAL_SERVER_PORT);
- rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr));
- if(rc<0) {
- printf("%s: cannot bind port number %d \n",
- argv[0], LOCAL_SERVER_PORT);
- exit(1);
- }
- printf("%s: waiting for data on port UDP %u\n",
- argv[0],LOCAL_SERVER_PORT);
- /* server infinite loop */
- int i = 1;
- while(1) {
- /* init buffer */
- memset(msg,0x0,MAX_MSG);
- /* receive message */
- cliLen = sizeof(cliAddr);
- n = recvfrom(sd, msg, MAX_MSG, 0,
- (struct sockaddr *) &cliAddr, &cliLen);
- printCurrentTime();
- if(n<0) {
- //printf("%s: cannot receive data \n",argv[0]);
- continue;
- }
- /* print received message */
- //printf("%s: from %s:UDP%u : %s \n",
- //argv[0],inet_ntoa(cliAddr.sin_addr),
- //ntohs(cliAddr.sin_port),msg);
- //printf ("(%d)\n", i++);
- }/* end of server infinite loop */
- return 0;
- }
- void printCurrentTime() {
- char buffer[26];
- int millisec;
- struct tm* tm_info;
- struct timeval tv;
- gettimeofday(&tv, NULL);
- millisec = lrint(tv.tv_usec/1000.0); // Round to nearest millisec
- if (millisec>=1000) { // Allow for rounding up to nearest second
- millisec -=1000;
- tv.tv_sec++;
- }
- tm_info = localtime(&tv.tv_sec);
- strftime(buffer, 26, "%Y:%m:%d %H:%M:%S", tm_info);
- printf("%s.%03d\n", buffer, millisec);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement