Listen on com port [closed]
Want to improve开发者_如何学运维 this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this questioni am writing a program in C and i wanna know how can i listen on com port and read the data from it please help me thanks
I'm not sure what you are looking for, but this could be of some help, its in Unix:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <bstring.h> /* bzero(), bcopy() */
#include <unistd.h> /* read(), write(), close() */
#include <errno.h>
#include <sys/signal.h>
int obtain_socket(int port);
void show_message(int sd);
void close_down(int sigtype);
#define PORT 2001 /* default port for server */
#define SIZE 512 /* max length of character string */
int ssockfd; /* socket for PORT; global for close_down() */
int main()
{
int sd, client_len;
struct sockaddr_in client;
signal(SIGINT, close_down); /* use close_down() to terminate */
printf("Listen starting on port %d\n", PORT);
ssockfd = obtain_socket(PORT);
while(1) {
client_len = sizeof(client);
if ((sd = accept(ssockfd, (struct sockaddr *) &client,
&client_len)) < 0) {
perror("accept connection failure");
exit(4);
}
show_message(sd);
close(sd);
}
return 0;
}
int obtain_socket(int port)
/* Perform the first four steps of creating a server:
create a socket, initialise the address data structure,
bind the address to the socket, and wait for connections.
*/
{
int sockfd;
struct sockaddr_in serv_addr;
/* open a TCP socket */
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
perror("could not create a socket");
exit(1);
}
/* initialise socket address */
bzero((char *)&serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(port);
/* bind socket to address */
if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
perror("could not bind socket to address");
exit(2);
}
/* set socket to listen for incoming connections */
/* allow a queue of 5 */
if (listen(sockfd, 5) == -1) {
perror("listen error");
exit(3);
}
return sockfd;
}
void show_message(int sd)
/* Print the incoming text to stdout */
{
char buf[SIZE];
int no;
while ((no = read(sd, buf, SIZE)) > 0)
write(1, buf, no); /* write to stdout */
}
void close_down(int sigtype)
/* Close socket connection to PORT when ctrl-C is typed */
{
close(ssockfd);
printf("Listen terminated\n");
exit(0);
}
For Linux you have the Serial Programming HOWTO.
精彩评论