侧边栏壁纸
博主头像
Hoo - Dev Tools Kit

开发工具箱

  • 累计撰写 5 篇文章
  • 累计创建 0 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

本地 git 出现无法连接 GitHub 的解决方法

Hoo
Hoo
2025-03-19 / 0 评论 / 0 点赞 / 10 阅读 / 0 字

本地 git 出现无法连接 GitHub 的解决方法

很奇怪,昨天早上还能正常的用 git 连接我的 GitHub 账户,到了晚上我要提交笔记的时候就告诉我 22 端口被拒绝访问。我尝试了网上各种方法,比如更改访问的端口为 443、将 GitHub 改用代理的形式连接、还有是建议我用 https + token 连接(但这一步我没尝试,因为我觉得 ssh 更加方便),但都无济于事。

问题的发现

我在 ping github.com 的时候发现 ping 的地址是我本地的 127.0.0.1 [::1] ,而 127.0.0.1 是属于私有地址。

众所周知,私有地址无论如何是不会映射到公网域名,如果ping某个域名返回的是私有地址,那么只有一种可能,要么DNS的解析出现问题,要么本地Host将域名映射不到某个私有地址。—— ping github,io 结果为 127.0.0.1 的问题分析及解决办法

接下来我找到 hosts 文件,查看里面是否有跟 github.com 有关的记录:

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#	127.0.0.1       localhost
#	::1             localhost

没有。那就说明 DNS 出了问题,接着我尝试使用更改本地的 DNS 为 8.8.8.8 和 8.8.4.4,但依旧不行。

解决方法

最后我用了最简单粗暴的方式,就是在 hosts 文件里直接加上 github.com 的真实 ip,真实 ip 的查找方法:

访问 https://www.ipaddress.com/website/github.com,在页面中间有一条记录:140.82.113.4。于是更改 hosts 文件为:

...
# localhost name resolution is handled within DNS itself.
#	127.0.0.1       localhost
#	::1             localhost
140.82.113.4     github.com

接着我再 ping github.com 就能正常的定位到了。

C:\Windows\System32\drivers\etc>ping github.com

Pinging github.com [140.82.113.4] with 32 bytes of data:
Reply from 140.82.113.4: bytes=32 time=212ms TTL=47
Reply from 140.82.113.4: bytes=32 time=212ms TTL=47
Reply from 140.82.113.4: bytes=32 time=214ms TTL=47
Reply from 140.82.113.4: bytes=32 time=212ms TTL=47

Ping statistics for 140.82.113.4:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 212ms, Maximum = 214ms, Average = 212ms

最后,尝试用 git 连接 GitHub:

$ ssh -T git@github.com
Hi YOURUSERNAME! You've successfully authenticated, but GitHub does not provide shell access.

成功🎉🥳🍾🥂🎊

0

评论区