2012-07-19 113 views
1

我試圖創建一個程序,它能夠創建和發送tcp包,但在編譯時不斷收到這些錯誤。未聲明的變量和預期的標識符錯誤

error: expected identifier or ‘(’ before ‘,’ token 

error: ‘sin’ undeclared (first use in this function) 
error: ‘din’ undeclared (first use in this function) 

現在,我敢肯定,這些都是一些真正明顯的結果,但我盯着自己盲目的這段代碼並不能得到我的頭周圍。功能如下:

int send_tcp() 
     { 
      int sock, one = 1; 
      char buffer[PCKT_LEN]; 
      struct sockaddr_in, sin, din; 
      const int *val = &one; 

      sock = socket(PF_INET, SOCK_RAW, IPPROTO_TCP); 
      if (sock < 0) 
       { 
        printf("\nError: socket()\n\n"); 
        exit (-1); 
       } 
      else 
        printf ("\nsocket() - Using SOCK_RAW and TCP protocol is OK.\n\n"); 

      /* Size of the headers */   
      struct ipheader *ip = (struct ipheader *) buffer; 
      struct tcpheader *tcp = (struct tcpheader *) (buffer + sizeof (struct ipheader)); 
      memset (buffer, 0, PCKT_LEN); 

      /* IP attributes */ 
      ip->iph_ihl = 5; 
      ip->iph_ver = 4; 
      ip->iph_tos = 16; 
      ip->iph_len = sizeof(struct ipheader) + sizeof(struct tcpheader); 
      ip->iph_id = htons(54321); 
      ip->iph_offset = 0; 
      ip->iph_ttl = 64; 
      ip->iph_protocol = 6; 
      ip->iph_chksum = 0; 

      ip->iph_sourceip = sip; 
      ip->iph_destip = dip; 

      /* TCP attributes */ 
      tcp->tcph_sourceport = sport; 
      tcp->tcph_destport = dport; 

      tcp->tcph_seqnum = htonl(1); 
      tcp->tcph_acknum = 0; 
      tcp->tcph_offset = 5; 
      tcp->tcph_syn = 1; 
      tcp->tcph_ack = 0; 
      tcp->tcph_win = htons(32767); 
      tcp->tcph_chksum = 0; 
      tcp->tcph_urgptr = 0; 

      ip->iph_chksum = checksum ((unsigned short *) buffer, (sizeof (struct ipheader)+ sizeof (struct tcpheader))); 

      /* Address family */ 
      sin.sin_family = AF_INET; 
      din.sin_family = AF_INET; 

      /* Source port */ 
      sin.sin_port = sport; 
      din.sin_port = dport; 

      /* Source IP */ 
      sin.sin_addr.s_addr = sip; 
      din.sin_addr.s_addr = dip;  

      /* Tell the Kernel we're building our own packet */ 
      if ((setsockopt(sock, IPPROTO_IP, IP_HDRINCL, (char *)&one, sizeof (one))) < 0) 
       { 
        printf("\nError: Can't set socketoptions\n\n"); 
        return (-1); 
       } 

      /* Send */ 
      if (sendto(sock, buffer, ip->iph_len, 0, (struct sockaddr *)&sin, sizeof(sin)) < 0) 
       { 
        printf("\nError: Can't send packet\n\n"); 
        return (-1); 
       } 

      else 
        printf("Packet sent to %s", dip); 

      close(sock); 
     }   

我的印象是:

struct sockaddr_in, sin, din; 

就足夠了,但它不是obiously。這也是預期標識符錯誤消息指向的行。我錯過了什麼?

回答

4

刪除第一個逗號

struct sockaddr_in, sin, din; 
       ^
       ^

sockaddr_in是一個結構的,所以我跟你想聲明一個名爲sindinsockadddr_in類型的兩個變量上面的行假設名稱。如果是這樣,您需要刪除該逗號作爲struct sockaddr_in之後的變量名稱。你所做的是一樣的嘗試以下操作:

int, a,b; 

也不會因爲馬上編譯類型名int編譯後需要一個變量名。

刪除那個逗號,你不應該得到你的編譯錯誤。

+0

工作!非常感謝。就是那些小東西......太討厭了。 – youjustreadthis 2012-07-19 20:18:15