听com端口

时间:2010-02-09 06:42:42

标签: c

我正在用C编写一个程序,我想知道如何在com端口上进行监听 并从中读取数据 请帮我 感谢

2 个答案:

答案 0 :(得分:1)

我不确定你在寻找什么,但这可能会有所帮助,它在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);
}

答案 1 :(得分:0)

对于Linux,您拥有Serial Programming HOWTO