elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.

 

 


Tema destacado: Introducción a Git (Primera Parte)


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación General
| | |-+  .NET (C#, VB.NET, ASP)
| | | |-+  Programación Visual Basic (Moderadores: LeandroA, seba123neo)
| | | | |-+  NetStat + ProcessID
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] Ir Abajo Respuesta Imprimir
Autor Tema: NetStat + ProcessID  (Leído 3,239 veces)
srJ

Desconectado Desconectado

Mensajes: 5


Estadístico teórico


Ver Perfil
NetStat + ProcessID
« en: 29 Agosto 2016, 16:45 pm »

Hola Amigos selectos, necesito una ayudita

Estoy escribiendo un programita, en VB6, es del tipo TcpView, que me dice el IP local:puerto Local, IP Remota:Puerto remoto, y nombre de Host Remoto.

como le hago para agregar, tambien, el PID del proceso que habre una conexion?? busque en google pero solo encontré el source para VB.net


En línea

°°° Lo imposible solo tarda un poco más °°°
Eleкtro
Ex-Staff
*
Desconectado Desconectado

Mensajes: 9.806



Ver Perfil
Re: NetStat + ProcessID
« Respuesta #1 en: 29 Agosto 2016, 21:55 pm »

Hola

como le hago para agregar, tambien, el PID del proceso que habre una conexion??

Especifica cual es la información que actualmente conoces del proceso asociado a "X" conexión, si por ejemplo conoces el handle entonces puedes la solución más sencilla sería utilizar la función Win32 GetProcessId:

Saludos


« Última modificación: 29 Agosto 2016, 21:57 pm por Eleкtro » En línea

okik


Desconectado Desconectado

Mensajes: 462


Ver Perfil
Re: NetStat + ProcessID
« Respuesta #2 en: 30 Agosto 2016, 13:39 pm »

Código
  1. Dim strComputer As String
  2. Dim sReturn As String
  3. Dim strNameOfUser As Variant
  4. Dim colProcesses As Object
  5. Dim objProcess As Object
  6. strComputer = "." '"." local or "\\ComputerName"
  7. Set colProcesses = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2").ExecQuery("Select * from Win32_Process")
  8. For Each objProcess In colProcesses
  9. sReturn = objProcess.GetOwner(strNameOfUser)
  10. If sReturn <> 0 Then
  11. MsgBox "No se pudo obtener información de propietario para el proceso de " & objProcess.Name & ", PID: " & objProcess.processId & vbNewLine & "Error = " & sReturn
  12. Else
  13. MsgBox "Process " & objProcess.Name & ", PID: " & objProcess.processId & " is owned by " & "\" & strNameOfUser & "."
  14. End If
  15. Next
  16.  

Fuentes:
http://www.vbforums.com/showthread.php?355203-RESOLVED-How-to-get-process-information


GetOwner method of the Win32_Process class

Win32_Process class




« Última modificación: 30 Agosto 2016, 19:54 pm por okik » En línea

srJ

Desconectado Desconectado

Mensajes: 5


Estadístico teórico


Ver Perfil
Re: NetStat + ProcessID
« Respuesta #3 en: 30 Agosto 2016, 23:05 pm »

Gracias por contestar tan rapido! veo que están afiladisimos  ;-)

Este es el code que estoy modificando (lo saque de la Api-Guide :P)
le agregué un modulo que me devuelve, apartir de la IP-remota, el HostName remoto y ademas crea una cache.. pero no le encontré como agregar el proceso que habre el puerto.

mi intension es lograrlo unicamente con las Api (Gracias Elektro no logre como agregar GetProcesId, y a okik por el aporte)

Asi que este es el code, seguro a alguien le va servir

Form1
Código
  1. Option Explicit
  2.  
  3. Private Type MIB_TCPROW
  4.    dwState As Long
  5.    dwLocalAddr As Long
  6.    dwLocalPort As Long
  7.    dwRemoteAddr As Long
  8.    dwRemotePort As Long
  9. End Type
  10.  
  11. Private Const ERROR_SUCCESS            As Long = 0
  12. Private Const MIB_TCP_STATE_CLOSED     As Long = 1
  13. Private Const MIB_TCP_STATE_LISTEN     As Long = 2
  14. Private Const MIB_TCP_STATE_SYN_SENT   As Long = 3
  15. Private Const MIB_TCP_STATE_SYN_RCVD   As Long = 4
  16. Private Const MIB_TCP_STATE_ESTAB      As Long = 5
  17. Private Const MIB_TCP_STATE_FIN_WAIT1  As Long = 6
  18. Private Const MIB_TCP_STATE_FIN_WAIT2  As Long = 7
  19. Private Const MIB_TCP_STATE_CLOSE_WAIT As Long = 8
  20. Private Const MIB_TCP_STATE_CLOSING    As Long = 9
  21. Private Const MIB_TCP_STATE_LAST_ACK   As Long = 10
  22. Private Const MIB_TCP_STATE_TIME_WAIT  As Long = 11
  23. Private Const MIB_TCP_STATE_DELETE_TCB As Long = 12
  24.  
  25. Private Declare Function GetTcpTable Lib "iphlpapi.dll" (ByRef pTcpTable As Any, ByRef pdwSize As Long, ByVal bOrder As Long) As Long
  26. Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (dst As Any, src As Any, ByVal bcount As Long)
  27. Private Declare Function lstrcpyA Lib "kernel32" (ByVal RetVal As String, ByVal Ptr As Long) As Long
  28. Private Declare Function lstrlenA Lib "kernel32" (ByVal Ptr As Any) As Long
  29. Private Declare Function inet_ntoa Lib "wsock32.dll" (ByVal addr As Long) As Long
  30. Private Declare Function ntohs Lib "wsock32.dll" (ByVal addr As Long) As Long
  31.  
  32. Public iphDNS As New IPHostResolver
  33.  
  34. Public Function GetInetAddrStr(Address As Long) As String
  35.    GetInetAddrStr = GetString(inet_ntoa(Address))
  36. End Function
  37.  
  38. Private Sub ListView1_ColumnClick(ByVal ColumnHeader As ColumnHeader)
  39.    ListView1.SortKey = ColumnHeader.Index - 1
  40.    ListView1.SortOrder = Abs(Not ListView1.SortOrder = 1)
  41.    ListView1.Sorted = True
  42. End Sub
  43.  
  44. Public Function GetString(ByVal lpszA As Long) As String
  45.    GetString = String$(lstrlenA(ByVal lpszA), 0)
  46.    Call lstrcpyA(ByVal GetString, ByVal lpszA)
  47. End Function
  48.  
  49.  
  50. Private Sub Command1_Click()
  51.  
  52. Dim TcpRow As MIB_TCPROW
  53. Dim buff() As Byte
  54. Dim lngRequired As Long
  55. Dim lngStrucSize As Long
  56. Dim lngRows As Long
  57. Dim lngCnt As Long
  58. Dim strTmp As String
  59. Dim lstLine As ListItem
  60.  
  61. If ListView1.ListItems.Count <> 0 Then ListView1.ListItems.Clear
  62. Call GetTcpTable(ByVal 0&, lngRequired, 1)
  63.  
  64. If lngRequired > 0 Then
  65.    ReDim buff(0 To lngRequired - 1) As Byte
  66.    If GetTcpTable(buff(0), lngRequired, 1) = ERROR_SUCCESS Then
  67.        lngStrucSize = LenB(TcpRow)
  68.        'first 4 bytes indicate the number of entries
  69.        CopyMemory lngRows, buff(0), 4
  70.  
  71.        For lngCnt = 1 To lngRows
  72.            'moves past the four bytes obtained above to get data and cast into a TcpRow stucture
  73.            CopyMemory TcpRow, buff(4 + (lngCnt - 1) * lngStrucSize), lngStrucSize
  74.            'sends results to the listview
  75.  
  76.            With TcpRow
  77.                Set lstLine = ListView1.ListItems.Add(, , GetInetAddrStr(.dwLocalAddr) & ":" & ntohs(.dwLocalPort))
  78.                lstLine.SubItems(1) = GetInetAddrStr(.dwRemoteAddr) & ":" & ntohs(.dwRemotePort)
  79.                'lstLine.SubItems(2) =
  80.  
  81.                Select Case .dwState
  82.                    Case MIB_TCP_STATE_CLOSED:       strTmp = "Closed"
  83.                    Case MIB_TCP_STATE_LISTEN:       strTmp = "Listening"
  84.                    Case MIB_TCP_STATE_SYN_SENT:     strTmp = "Sent"
  85.                    Case MIB_TCP_STATE_SYN_RCVD:     strTmp = "Received"
  86.                    Case MIB_TCP_STATE_ESTAB:        strTmp = "Established"
  87.                    Case MIB_TCP_STATE_FIN_WAIT1:    strTmp = "Fin wait 1"
  88.                    Case MIB_TCP_STATE_FIN_WAIT2:    strTmp = "Fin wait 1"
  89.                    Case MIB_TCP_STATE_CLOSE_WAIT:   strTmp = "Close wait"
  90.                    Case MIB_TCP_STATE_CLOSING:      strTmp = "Closing"
  91.                    Case MIB_TCP_STATE_LAST_ACK:     strTmp = "Last ack"
  92.                    Case MIB_TCP_STATE_TIME_WAIT:    strTmp = "Time wait"
  93.                    Case MIB_TCP_STATE_DELETE_TCB:   strTmp = "TCB deleted"
  94.                End Select
  95.  
  96.                 lstLine.SubItems(2) = (.dwState) & " (" & strTmp & ")"
  97.                 lstLine.SubItems(3) = iphDNS.AddressToName(GetInetAddrStr(.dwRemoteAddr))
  98. '                 lstLine.SubItems(4) = ""
  99.                 strTmp = ""
  100.            End With
  101.  
  102.        Next lngCnt
  103.  
  104.    End If
  105. End If
  106.  
  107. End Sub
  108.  

Módulo que devuelve el HostName apartir de una IP
Código
  1. Option Explicit
  2.  
  3. Private mbInitialized As Boolean
  4. Private dictCache As New Dictionary
  5. Private intMaxCacheSize As Integer
  6.  
  7. Const WSADescription_Len = 256
  8. Const WSASYS_Status_Len = 128
  9.  
  10. Const AF_INET = 4&
  11.  
  12. Private Type HOSTENT
  13.  hName As Long
  14.  hAliases As Long
  15.  hAddrType As Integer
  16.  hLength As Integer
  17.  hAddrList As Long
  18. End Type
  19.  
  20. Private Type WSADATA
  21.  wversion As Integer
  22.  wHighVersion As Integer
  23.  szDescription(0 To WSADescription_Len) As Byte
  24.  szSystemStatus(0 To WSASYS_Status_Len) As Byte
  25.  iMaxSockets As Integer
  26.  iMaxUdpDg As Integer
  27.  lpszVendorInfo As Long
  28. End Type
  29.  
  30. Private Declare Function WSAStartup Lib "wsock32" (ByVal VersionReq As Long, WSADataReturn As WSADATA) As Long
  31. Private Declare Function WSACleanup Lib "wsock32" () As Long
  32. Private Declare Function WSAGetLastError Lib "wsock32" () As Long
  33. Private Declare Function gethostbyaddr Lib "wsock32" (addr As Long, addrLen As Long, addrType As Long) As Long
  34. Private Declare Function gethostbyname Lib "wsock32" (ByVal hostname As String) As Long
  35. Private Declare Sub RtlMoveMemory Lib "kernel32" (hpvDest As Any, ByVal hpvSource As Long, ByVal cbCopy As Long)
  36.  
  37. 'checks if string is valid IP address
  38. Private Function CheckIP(IPToCheck As String) As Boolean
  39.  Dim TempValues
  40.  Dim iLoop As Long
  41.  Dim TempByte As Byte
  42.  
  43.  TempValues = Split(IPToCheck, ".")
  44.  
  45.  If UBound(TempValues) < 3 Then
  46.    Exit Function
  47.  End If
  48.  
  49.  For iLoop = LBound(TempValues) To UBound(TempValues)
  50.    TempByte = TempValues(iLoop)
  51.  Next iLoop
  52.  CheckIP = True
  53.  
  54. End Function
  55.  
  56. 'converts IP address from string to sin_addr
  57. Private Function MakeIP(strIP As String) As Long
  58.  Dim vTemp
  59.  Dim lngTemp As Long
  60.  Dim iLoop As Long
  61.  
  62.  vTemp = Split(strIP, ".")
  63.  
  64.  For iLoop = 0 To (UBound(vTemp) - 1)
  65.    lngTemp = lngTemp + (vTemp(iLoop) * (256 ^ iLoop))
  66.  Next iLoop
  67.  
  68.  If vTemp(UBound(vTemp)) < 128 Then
  69.    lngTemp = lngTemp + (vTemp(UBound(vTemp)) * (256 ^ 3))
  70.  Else
  71.    lngTemp = lngTemp + ((vTemp(UBound(vTemp)) - 256) * (256 ^ 3))
  72.  End If
  73.  
  74.  MakeIP = lngTemp
  75. End Function
  76.  
  77. 'resolves IP address to host name
  78. Private Function AddrToName(strAddr As String) As String
  79.  
  80.  Dim heEntry As HOSTENT
  81.  Dim strHost As String * 255
  82.  Dim strTemp As String
  83.  Dim lngRet As Long
  84.  Dim lngIP As Long
  85.  
  86.  If CheckIP(strAddr) Then
  87.    lngIP = MakeIP(strAddr)
  88.    lngRet = gethostbyaddr(lngIP, 4, AF_INET)
  89.    If lngRet = 0 Then
  90.      Exit Function
  91.    End If
  92.    RtlMoveMemory heEntry, lngRet, Len(heEntry)
  93.    RtlMoveMemory ByVal strHost, heEntry.hName, 255
  94.    strTemp = TrimNull(strHost)
  95.    AddrToName = strTemp
  96.  End If
  97.  
  98. End Function
  99.  
  100. Public Function AddressToName(strIP As String) As String
  101.    Dim strCache As String
  102.    If mbInitialized Then
  103.        On Error Resume Next
  104.        If dictCache.Exists(strIP) Then
  105.            AddressToName = dictCache(strIP)
  106.        Else
  107.            Err.Clear
  108.            AddressToName = AddrToName(strIP)
  109.            dictCache.Add strIP, AddressToName
  110.            While dictCache.Count > intMaxCacheSize
  111.                dictCache.Remove dictCache.Keys(UBound(dictCache.Items))
  112.            Wend
  113.        End If
  114.    End If
  115. End Function
  116.  
  117. Private Function TrimNull(sTrim As String) As String
  118.  Dim iFind As Long
  119.  iFind = InStr(1, sTrim, Chr(0))
  120.  If iFind > 0 Then
  121.    TrimNull = Left(sTrim, iFind - 1)
  122.  Else
  123.    TrimNull = sTrim
  124.  End If
  125. End Function
  126.  
  127. Private Sub Class_Initialize()
  128.  Dim wsa As WSADATA
  129.  Dim ff As Byte
  130.  Dim strIP As String, strDomain As String
  131.  
  132.  mbInitialized = (WSAStartup(257, wsa) = 0)
  133.  intMaxCacheSize = Val(GetSetting(App.ProductName, "Cache", "MaxSize", 100))
  134.  
  135.  'Read in the cache file
  136.  ff = FreeFile
  137.  On Error Resume Next
  138.  Open GetSetting(App.ProductName, "Cache", "Filename", App.Path & "\cache.dat") For Input As #ff
  139.    While Not EOF(ff)
  140.        Input #ff, strIP, strDomain
  141.        dictCache.Add strIP, strDomain
  142.    Wend
  143.  Close #ff
  144. End Sub
  145.  
  146. Private Sub Class_Terminate()
  147.  Dim ff As Byte
  148.  Dim strKey As Variant
  149.  
  150.  If mbInitialized Then
  151.    WSACleanup
  152.  
  153.    'Save the cache to a file
  154.    ff = FreeFile
  155.    Open GetSetting(App.ProductName, "Cache", "Filename", App.Path & "\cache.dat") For Output As #ff
  156.        For Each strKey In dictCache.Keys
  157.            Print #ff, strKey & "," & dictCache(strKey)
  158.        Next
  159.    Close #ff
  160.  End If
  161. End Sub
  162.  


Hola

Especifica cual es la información que actualmente conoces del proceso asociado a "X" conexión, si por ejemplo conoces el handle entonces puedes la solución más sencilla sería utilizar la función Win32 GetProcessId:

Saludos

estoy utilizando el api GetTcpTable pero nosé como sacarle de ahi el handle para localizar el proceso. arriva dejé mi code pára que lo examines amigo.

lei por ahi que en WinXP, lo que quiero, se consigue con AllocateAndGetTcpExTableFromStack() and AllocateAndGetUdpExTableFromStack().
pero mi sistema es Win7 32bits y esas Api no me funcionan, :-\



Amigos alguna pista?? busco y busco, no doy con la solucción  :P
Quiero hacer un programita como TcpView en [VB6]

Solo quiero saber ¿como agregarle el Nombre de Proceso y el PID??  :huh: hasta ahora logré lo siguiente..



Ayudaa Please!

MOD EDIT: No hacer triple post.
« Última modificación: 1 Septiembre 2016, 16:22 pm por MCKSys Argentina » En línea

°°° Lo imposible solo tarda un poco más °°°
Páginas: [1] Ir Arriba Respuesta Imprimir 

Ir a:  

Mensajes similares
Asunto Iniciado por Respuestas Vistas Último mensaje
IP por netstat en VB
Programación Visual Basic
Hendrix 4 5,182 Último mensaje 12 Febrero 2006, 09:16 am
por maurivi
netstat en un ciber cafe netstat
Redes
warez_skate 1 3,638 Último mensaje 9 Mayo 2011, 02:32 am
por ThonyMaster
Duda sobre netstat
Dudas Generales
Kilerj7 1 2,346 Último mensaje 27 Abril 2022, 10:46 am
por el-brujo
WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines